![](/img/trans.png)
[英]How do I get a program to print the number of words in a sentence and each word in order
[英]How do I convert each of the words to a number?
我正在嘗試讀取文件並用數字覆蓋其內容。 這意味着對於第一個單詞,它將是 1,對於第二個單詞,它將是 2,依此類推。
這是我的代碼:
file=open("reviews.txt","r+")
i=1
for x in file:
line=file.readline()
word=line.split()
file.write(word.replace(word,str(i)))
i+=1
file.close()
輸入文件:
This movie is not so good
This movie is good
預期的 output 文件:
1 2 3 4 5 6
7 8 9 10
在編譯期間,我不斷收到錯誤消息: AttributeError: 'list' object has no attribute 'replace'
。 列表 object 是哪一個? 據我所知,所有變量都是字符串。 請幫我。
對split
的調用返回一個列表,您需要對其進行迭代以處理每個單詞的替換:
with open("reviews.txt", "r+") as file:
i = 1
line = file.readline()
while line:
words = line.split()
for item in words:
file.write(str(i) + ' ')
i += 1
line = file.readline()
file.close()
可以先使用您喜歡的任何方法創建 output,然后在文件中寫入一次。 也許,循環中的file.write
不是那么必要。
我們打開文件,獲取其所有內容,然后關閉它。
在DOTALL
模式下使用re
模塊,我們將在第一個捕獲組中得到我們想要替換的任何內容,在這種情況下,使用(\S+)
或(\w+)
等,然后我們在第二個捕獲中收集所有其他字符使用(.+?)
分組,然后使用re.findall
,我們將在列表中生成兩個元素的元組,我們想要替換這些元組的第一個元素。
然后我們編寫一個循環,用遞增計數器替換第一組,這是這里的想法,第二組保持不變,我們將逐步將兩者作為我們的新內容連接到string_out
我們最后打開 [empty] 文件,寫入string_out
,然后關閉它。
import re
file = open("reviews.txt","r+")
word_finder, counter, string_out = re.findall(r"(\S+)|(.+?)", file.read(), re.DOTALL), 0, ''
file.close()
for item in word_finder:
if item[0]:
counter += 1
string_out += str(counter)
else:
string_out += item[1]
try:
file = open("reviews.txt","w")
file.write(string_out)
finally:
file.close()
1 2 3 4 5 6
7 8 9 10
如果您希望簡化/修改/探索表達式,它已在regex101.com的右上角面板中進行了說明。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.