【发布时间】:2026-02-15 08:10:02
【问题描述】:
我想检查一个单词在文件中重复了多少次。我已经看到了在文件中查找单词的其他代码,但它们不能解决我的问题。从这里我的意思是如果我想找到“Python 是我最喜欢的语言”程序将分割文本将告诉它重复了多少次文件。
def search_tand_export():
file = open("mine.txt")
#targetlist = list()
#targetList = [line.rstrip() for line in open("mine.txt")]
contentlist = file.read().split(" ")
string=input("search box").split(" ")
print(string)
fre={}
outputfile=open("outputfile.txt",'w')
for word in contentlist:
print(word)
for i in string:
# print(i)
if i == word:
print(f"'{string}' is in text file ")
outputfile.write(word)
print(word)
spl=tuple(string.split())
for j in range(0,len(contentist)):
if spl in contentlist:
fre[spl]+=1
else:
fre[spl]=1
sor_list=sorted(fre.items(),key =lambda x:x[1])
for x,y in sor_list:
print(f"Word\tFrequency")
print(f"{x}\t{y}")
else:
continue
print(f"The word or collection of word is not present")
search_tand_export()
【问题讨论】:
标签: python list dictionary file-handling