[英]find words in txt files Python 3
我想在python 3中创建一个程序,以查找特定单词在txt文件中出现多少次,然后用这些值构建一个excel表格。 我做了这个函数,但是最后我想起函数并输入内容时,程序无法正常工作。 出现这句话:unindent不匹配任何外部缩进级别
def wordcount(filename, listwords):
try:
file = open( filename, "r")
read = file.readlines()
file.close()
for x in listwords:
y = x.lower()
counter = 0
for z in read:
line = z.split()
for ss in line:
l = ss.lower()
if y == l:
counter += 1
print(y , counter)
现在,我尝试使用txt文件和要查找的单词来调用该函数
wordcount("aaa.txt" , 'word' )
喜欢输出,我想看
word 4
感谢大家!
这是一个示例,可用于查找特定单词在文本文件中的停留时间;
def searching(filename,word):
counter = 0
with open(filename) as f:
for line in f:
if word in line:
print(word)
counter += 1
return counter
x = searching("filename","wordtofind")
print(x)
输出将是您尝试查找的单词及其出现的时间。
尽可能短:
def wordcount(filename, listwords):
with open(filename) as file_object:
file_text = file_object.read()
return {word: file_text.count(word) for word in listwords}
for word, count in wordcount('aaa.txt', ['a', 'list', 'of', 'words']).items():
print("Count of {}: {}".format(word, count))
回到mij关于将listwofwords
作为实际列表传递的评论:如果将字符串传递给需要列表的代码,python会将字符串解释为字符列表,如果这种行为不熟悉,可能会造成混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.