python - 使用 python 的正则表达式不起作用

标签 python regex python-2.7

import re
sum=0
file = open("pro.txt").readlines()
for lines in file:
        word= len(re.findall('(^|[^\w\-])able#1(?=([^\w\-]|$))', lines))
        if word>0:
                sum=sum+1
print sum

我正在计算文本文件中的单词数,但我的程序也计算了一些不是我们需要的单词,我在其中使用了 r.e ,但它没有给我任何适当的帮助 这是我的文本文件

0         6          9     able#1
0         11         34    unable#1
9         12         22    able#1
0         6          9     able#1-able#1
0         11         34    unable#1*able#1

我不希望我的程序计算 ,-able#1 ,able#1-able#1 ,unable#1*able#1 这些类型的单词,我应该只计算 能够#1

最佳答案

您可以使用正则表达式 \sable#1\s*$,它要求 able 之前有一个空格,并在末尾允许零个或多个空格(没有其他内容)线路。

import re
regex = re.compile(r'\sable#1\s*$')
count = 0
with open("pro.txt") as file:
    for line in file:
        if regex.search(line):
            count += 1
print count

您还可以使用 sum() 和生成器表达式进行计数,如下所示:

with open("pro.txt") as file:
    count = sum(1 for line in file if regex.search(line))

关于python - 使用 python 的正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070815/

相关文章:

ruby-on-rails - 不以替换脚本结尾的电子邮件的正则表达式

regex - 如何替换字符串中的单/双字符

python - JSON 类型错误 : expected string or buffer

python - 在 Sqlite 中对多索引大型数据库表进行排序

python - 将标准输入和参数传递给脚本

python随机化保留每3个项目(列表的列表?)

单击其他地方时,Python3 Tkinter 弹出菜单不会自动关闭

python将字符串转换为运算符

php - preg_match_all 如何获得*所有*组合?甚至重叠的

python - 按以某个字符串开头的键对字典进行切片