【问题标题】:Using re.findall in a txt file [duplicate]在 txt 文件中使用 re.findall [重复]
【发布时间】:2018-03-25 13:13:21
【问题描述】:

我想使用re.findall 来检测一个单词在 .txt 文件中显示了多少次。另外,如果我要计算 Hello 一词出现在要检测的文本 Hellooo 中的次数,我还需要它。 p>

这是我所有的代码:

# -*- coding: utf-8 -*-
import re

total = 0

with open('text.txt') as f:
    for line in f:
        total = re.findall('Hello')

print total

【问题讨论】:

标签: python regex python-2.7


【解决方案1】:

为什么还要使用正则表达式?

count() 方法会做同样的事情:

with open('text.txt') as f:

    total = f.read()
    print total.count('Hello')

并且不需要导入模块,因为它是内置的。

当使用正则表达式时,也不建议使用r 作为原始字符串前缀。 total = re.findall(r'Hello')

【讨论】:

    【解决方案2】:

    创建文件:

    echo "Hellooo there.
    Hello hello Hello" > file.txt
    

    并找到所有出现的"Hello"

    In [1]: import re
    
    In [2]: with open('file.txt') as f:
       ...:     all_hellos = re.findall('Hello', f.read())
       ...:
    
    In [3]: print(len(all_hellos))
    3
    

    上面只会寻找Hello,而不是hello。这会将整个文件缓存在内存中,因此除非您使用大文件,否则这会很好。

    请记住,re.findall() 将返回找到的所有匹配项的列表,而不是出现次数。

    【讨论】:

    • 如果你不使用re.finditer来提高内存效率,为什么不直接使用str.count
    • @timgeb str.count 看起来不错。我从来不知道。我不知道用户是否想专门使用re.findall
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2018-08-02
    • 2019-07-17
    • 2012-12-05
    相关资源
    最近更新 更多