亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將文件中的單詞拆分并添加到列表中,“str”對象不能解釋為整數錯誤

將文件中的單詞拆分并添加到列表中,“str”對象不能解釋為整數錯誤

Go
陪伴而非守候 2022-01-18 13:48:28
我不知道此錯誤的原因,但我試圖獲取文件中的單詞,讀取行,拆分它們,然后將這些單詞添加到列表中并對它們進行排序。這很簡單,但我似乎收到一個錯誤,指出“'str'對象不能被解釋為整數'我不知道這個錯誤的原因,希望能得到一些幫助。我沒有嘗試過很多方法,因為我確信這個方法會起作用,而且我不知道如何繞過它。我正在使用的文件包含以下內容:But soft what light through yonder window breaksIt is the east and Juliet is the sunArise fair sun and kill the envious moonWho is already sick and pale with grief這是我正在使用的代碼...#userin = input("Enter file name: ")try:  l = [] # empty list  relettter = open('romeo.txt', 'r')  rd = relettter.readlines()   # loops through each line and reads file  for line in rd:    #add line to list    f = line.split(' ', '/n')    l.append(f)  k = set(l.sort())  print(k)except Exception as e:    print(e)結果應該打印出詩歌中出現的單詞的排序列表。
查看完整描述

3 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

您巨大的 try/except 塊會阻止您查看錯誤的來源。刪除:


? python romeo.py 

Traceback (most recent call last):

  File "romeo.py", line 9, in <module>

    f = line.split(' ', '/n')

TypeError: 'str' object cannot be interpreted as an integer

您將 '/n' 作為第二個參數傳遞給 split() 方法,它是一個 integer maxsplit。你的線


f = line.split(' ', '/n')

不起作用,因為 split 方法只能使用一個字符串,例如:


f = line.split(' ')

另請注意,'\n' 是換行符,而不是 '/n'。


查看完整回答
反對 回復 2022-01-18
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

當您拆分f = line.split(' ', '/n')而不是執行此操作時會導致錯誤f = line.split('\n')[0].split(' ')。同樣在下一個聲明中,我認為您會extend不想append


try:

    l = [] # empty list


    relettter = open('romeo.txt', 'r')

    rd = relettter.readlines() 


    # loops through each line and reads file

    for line in rd:


        #add line to list

        f = line.split('\n')[0].split(' ')   ##<-first error


        l.extend(f)                          ##<- next problem


    k = set(sorted(l))


    print(k)


except Exception as e:

    print(e)

雖然,一個更好的實現:


l = [] # empty list


with open('romeo.txt') as file:


    for line in file:

        f = line[:-1].split(' ')

        l.extend(f)


    k = set(sorted(l))

    print(k)


查看完整回答
反對 回復 2022-01-18
?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

您可能應該with在這種情況下使用。它本質上管理您原本不受管理的資源。這是一個很好的解釋:python 關鍵字“with”用于什么?.


至于你的問題:


with open(fname, "r") as f:

    words = []

    for line in f:

        line = line.replace('\n', ' ')

        for word in line.split(' '):

            words.append(word)

這將逐行讀取文本并將每行拆分為單詞。然后將單詞添加到列表中。


如果您正在尋找更短的版本:


with open(fname, "r") as f:

    words = [word for word in [line.replace('\n', '').split(' ') for line in f]]

這將給出每個句子的單詞列表,但是您可以以這種方式展平并獲取所有單詞。


查看完整回答
反對 回復 2022-01-18
  • 3 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號