[英]find words in txt files Python 3
I'd like to create a program in python 3 to find how many time a specific words appears in txt files and then to built an excel tabel with these values. 我想在python 3中创建一个程序,以查找特定单词在txt文件中出现多少次,然后用这些值构建一个excel表格。 I made this function but at the end when I recall the function and put the input, the progam doesn't work.
我做了这个函数,但是最后我想起函数并输入内容时,程序无法正常工作。 Appearing this sentence: unindent does not match any outer indentation level
出现这句话: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)
Now I try to recall the function with a txt file and the word to find 现在,我尝试使用txt文件和要查找的单词来调用该函数
wordcount("aaa.txt" , 'word' )
Like output I'd like to watch 喜欢输出,我想看
word 4
thanks to everybody ! 感谢大家!
Here is an example you can use to find the number of time a specific word is in a text file; 这是一个示例,可用于查找特定单词在文本文件中的停留时间;
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)
The output will be the word you try to find and the number of time it occur. 输出将是您尝试查找的单词及其出现的时间。
As short as possible: 尽可能短:
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))
Getting back to mij's comment about passing listwofwords
as an actual list: If you pass a string to code that expects a list, python will interpret the string as a list of characters, which can be confusing if this behaviour is unfamiliar. 回到mij关于将
listwofwords
作为实际列表传递的评论:如果将字符串传递给需要列表的代码,python会将字符串解释为字符列表,如果这种行为不熟悉,可能会造成混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.