我已经有了这个代码:
f = open("unknown.txt", 'r')
a = sum(line.count('ly').endswith() for line in f)
words = 0
with open("unknown.txt", 'r') as f:
words = len(f.read().split())
try:
percentage = a/words*100
print('{}% adverbs'.format(percentage))
except:
print('File is empty!')
但这一切所做的只是检查单词中是否有“ly”,我如何才能让它只算作“ly”if .endswith('ly')(我是猜测这些命令将被使用,但我不知道如何使用。有人可以让我的代码执行此操作吗?提前致谢!
最佳答案
你必须将你的行拆分成单词并测试每个单词:
a = sum(word.endswith('ly') for line in f for word in line.split())
这 (ab) 使用了 Python bool 值是 int
和 True
== 1 和 False
== 0 的子类这一事实.
您可以使用过滤器使其更明确:
a = sum(1 for line in f for word in line.split() if word.endswith('ly'))
然而,您可能希望将两个计数合并到一个循环中:
with open("unknown.txt", 'r') as f:
total = lycount = 0
for line in f:
words = line.split()
total += len(words)
lycount += sum(1 for word in words if word.endswith('ly'))
try:
percentage = (lycount / total) * 100
print('{}% adverbs'.format(percentage))
except ZeroDivisionError:
print('File is empty!')
请注意,您永远不应该使用 blanket except 语句;只是捕获特定的异常。
关于python - 如何从文件中检查单词是否以特定字符串结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527763/