python - 计算文件中句子单词重复的次数
问题描述
我想检查一个单词在文件中重复了多少次。我已经看到其他代码在文件中查找单词,但它们不能解决我的问题。从这里我的意思是如果我想找到“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()
解决方案
我不太明白你想做什么。但是我想您正在尝试找出给定句子中的每个单词在文件中重复的次数。
如果是这种情况,您可以尝试以下方法:
sentence = "Python is my favorite programming language"
words = sentence.split()
with open("file.txt") as fp:
file_data = fp.read()
for word in words:
print(f"{file_data.count(word)} occurence(s) of '{word}' found")
请注意,上面的代码区分大小写(即“Python”和“python”是不同的词)。为了使其不区分大小写,您可以file_data
在与小写比较的过程中使用str.lower()
.
sentence = "Python is my favorite programming language"
words = sentence.split()
with open("file.txt") as fp:
file_data = fp.read().lower()
for word in words:
print(f"{file_data.count(word.lower())} occurence(s) of '{word}' found")
有几点需要注意:
您正在打开一个文件,甚至最终都没有关闭它(尽管您应该这样做)。最好使用
with open(...) as ...
(context-manager),这样文件会自动关闭。Python 字符串(以及列表、元组等)具有
.count(what)
方法。它返回what
在对象中找到的出现次数。阅读 PEP-8 编码风格并为变量提供更好的名称。例如,要理解代码中的含义并不容易
fre
。但是如果你把它命名为frequency
,代码会变得更易读,也更容易使用。未完待续
推荐阅读
- javascript - 如何检查字符串是否仅由相同长度的字符组组成?
- javascript - Bootstrap 4 多选下拉菜单
- flutter - Flutter:自定义字体
- android - FFMPEG 源代码编译失败,Android NDK Clang 编译器(r16b)出现错误“clang 编译器不支持'-mcpu=arm'”
- mysql - 如何将 mysql 连接到我的 play slick scalaSlickTest 文件
- python - 如何沿给定轴(例如 2)在多维 numpy 数组中获取 N 个最大值?
- java - POI 读取 XLS /XLSX,复选框值 java
- php - 使用 PHPUnit 7 测试旧的 PHP 版本
- c++ - ZMQ 套接字连接超时
- html - 如何解决并排放置 div 的移动问题?