python - 如何从文件中检查单词是否以特定字符串结尾?

标签 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”if .endswith('ly')(我是猜测这些命令将被使用,但我不知道如何使用。有人可以让我的代码执行此操作吗?提前致谢!

最佳答案

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

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

这 (ab) 使用了 Python bool 值是 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!')

请注意,您永远不应该使用 blanket except 语句;只是捕获特定的异常。

关于python - 如何从文件中检查单词是否以特定字符串结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527763/

相关文章:

python - 使用属性序列化函数对象,加载时缺少一个属性

python - 如何在不旋转图像的情况下切换numpy中的图像表示

python - 估计卡方检验所需的样本量

python3 和请求 : still getting 'sslv3 alert handshake failure'

python - 如何在 python 上生成安全 session_id ?

python - 如何将 Django 与 Jade 结合起来

python - 在 Pandas DateTime 模块中设置一周的显式开始

python - 删除元组中列表列表中的项目

python-3.x - 如何在 shell 中并行运行 python 中的依赖脚本?

python - 如何从列表中添加一定范围的整数元素? Python 3.3