我正在编写一个程序,该文件从50,000个单词的文件中读取,并且需要获得其中没有字母“e”的单词的百分比。我可以让程序打印出没有e的所有单词,但我想将它们附加到列表中,以便我可以得到列表中元素的总和。我现在拥有的每次运行时都会得到0的结果。它还产生正确的总线数。对不起,我不是python中最好的。
f=open("hardwords.txt")
def has_no_e(f):
words = []
sum_words= len(words)
total = sum(1 for s in f)
print total
print sum_words
letter = 'e'
for line in f:
for l in letter:
if l in line:
break
else:
words.append(line)
has_no_e(f)
答案 0 :(得分:1)
你不需要收集单词,只计算它们。
未测试:
total = 0
without_e = 0
with open("hardwords.txt") as f:
for line in f:
total = total + 1
if not 'e' in line:
without_e = without_e + 1
percentage = float(without_e) / float(total)
答案 1 :(得分:0)
这个怎么样:
def has_no_e():
with open(path, "r") as f:
words = [word.strip() for line in f.readlines() for word in line.strip().split(',')]
words_without_e = [word for word in words if 'e' not in word]
print len(words), words
print len(words_without_e), words_without_e
has_no_e()
现在你只需要计算百分比
答案 2 :(得分:0)
就是这样:
def has_no_e(path):
total_words = 0
words_without_e = 0
with open(path, "r") as f:
for line in f:
words = line.lower().split()
total_words += len(words)
words_without_e += sum("e" not in w for w in words)
return (float(words_without_e)/total_words)*100
答案 3 :(得分:0)
这是一种可行的方法:
with open('G:\Tmp\demo.txt', 'r') as f:
total = 0
count = 0
for line in f:
words = line.split()
total = total + len(words)
count = count + len([w for w in words if w.find('e') > 0])
print 'Total word:{0}, counted:{1}'.format(total, count)