![](/img/trans.png)
[英]I made a timer program that counts number. and, Want to make the program more perfect by satisfying the conditions below. Can you give me some advice?
[英]I made a program that checks if a word in in a file, need some advice
如果單詞出現,我想打印,以及單詞出現在文件中的次數。 除了這個單詞在文件中出現1或0次之外,我無法說出來。
This problem occurs on line 26, print("It appears " + str(wordcount[word]) + " times")
特別是str(wordcount [word])。 這可能是一個簡單的問題,但這是我的第一周python,所以如果有人有想法請分享。 謝謝!
我試過把wordcount[word]
, word_counter.__getitem__(wordcount[word])
和word_counter.__getitem__(wordcount)
import collections
file = open(r"C:\Users\Patrick Wu\Documents\1wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read()
word = input("Word to check for :")
wordcount = {}
"""this below is to remove difference between upper and lower cases as
well as punctuation"""
for word in contents.lower().split():
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("“","")
word = word.replace("‘","")
word = word.replace("*","")
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
word_counter = collections.Counter(wordcount)
if word in str(contents):
print("This word is in the file :)")
print("It appears " + str(wordcount[word]) + " times")
else:
print("This word isn't in the file")
循環中,變量word
在本地范圍內被覆蓋。 因此,循環會覆蓋您的輸入word
,最后會檢查輸入文件的最后一個字的計數。 將輸入詞更改為與您在文件中迭代的詞不同的變量名。
您可以使用此代碼:
import collections
file = open("wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read().lower()
word = input("Word to check for :").lower()
times = 0
finish = 0
while finish==0:
if word in contents:
contents = contents[contents.find(word) + len(word):]
times += 1
else:
break
if times > 0:
print("This word is in the file :)")
print("It appears " + str(times) + " times")
else:
print("This word isn't in the file")
通過在輸入和for循環中使用相同的名稱“word”,您有一個范圍問題。
我建議做這樣的事情:
word = input("Word to check for :")
with open('your_file.txt') as f:
raw = f.read()
num_appearences = raw.count(word)
print(f"The word {word} appears {num_appearences} times in the file")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.