[英]Finding total number of words in .txt document
find = open("words.txt")
def noE():
for line in find:
if line.find("e") == -1:
word = line.strip()
print word,
noE()
The above code searches the .txt file for all words that do not contain the letter "e" and then prints them. 上面的代码在.txt文件中搜索不包含字母“ e”的所有单词,然后进行打印。 I would like to then be able to get a count of the total number of words under this if conditional. 如果有条件的话,我希望能够计算出该单词总数。 I looked into the python docs and found Count() but the import wasn't working for me (assuming I did something wrong). 我查看了python文档,发现Count(),但导入对我没有用(假设我做错了)。 Any help would be much appreciated! 任何帮助将非常感激!
Just add a counter variable inside of your for
loop. 只需在for
循环内添加一个计数器变量即可。
Also, don't use line.find('e')
. 另外,不要使用line.find('e')
。 Use the in
keyword instead: 改用in
关键字:
with open('words.txt', 'r') as handle:
total = 0
for line in handle:
if 'e' not in line:
total += 1
word = line.strip()
print word,
This would be more pythonic, and useful if you want to use the words for something else: 如果您想将这些词用于其他用途,这将更加Python化,并且很有用:
find = open("find.txt")
noes = [line.strip() for line in find if line.find("e")== -1]
print(noes)
print(len(noes))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.