我必須將前綴串列及其出現次數寫入一個新的文本檔案,只要前綴出現超過 1000 次。
我想出了這段代碼,但不知何故它不起作用。
output = prefix_list(file_name)
file = "testfile.txt"
for values in output:
if (values[1] >= 1000):
file.write(values[0] " " int(values[1]) "\n")
有人可以幫我解決我在這里做錯的事情嗎?
uj5u.com熱心網友回復:
您的代碼的問題是您似乎不知道如何讀取檔案。
如果你想用 Python 讀取檔案,你必須使用open內置函式,這樣:
with open('file.txt', 'r ') as file: #'r ' stands for read
text = file.read()
然后我會以這種方式計算“前綴”:
for i in text:
if (text.count(i) >= 1000):
# Do something
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419220.html
標籤:
上一篇:列出符合條件的所有值
