如何从文件中检查某个单词是否以某个字符串结尾?

时间:2013-08-30 07:54:46

标签: python python-3.x

我已经有了这段代码:

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'如果 .endswith('ly')(我是猜测这些命令将被使用,但我不知道如何。有人可以让我的代码做到这一点吗?提前谢谢!

1 个答案:

答案 0 :(得分:3)

你必须将你的行分成单词并测试每个单词:

a = sum(word.endswith('ly') for line in f for word in line.split())

这个(ab)使用的事实是Python布尔是intTrue == 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!')

请注意,除了声明外,你绝不应该使用毯子;只是抓住特定的例外。