首页 > 解决方案 > 使用正则表达式函数时返回值不一致

问题描述

我的代码表现得很奇怪,我感觉它与我正在使用的正则表达式有关。

我正在尝试确定文本文件中的总字数、唯一字数和句子数。

这是我的代码:

import sys
import re

file = open('sample.txt', 'r')


def word_count(file):
    words = []
    reg_ex = r"[A-Za-z0-9']+"
    p = re.compile(reg_ex)
    for l in file:
        for i in p.findall(l):
            words.append(i)
    return len(words), len(set(words))

def sentence_count(file):
    sentences = []
    reg_ex = r'[a-zA-Z0-9][.!?]'
    p = re.compile(reg_ex)
    for l in file: 
        for i in p.findall(l):
            sentences.append(i)
    return sentences, len(sentences)

sentence, sentence_count = sentence_count(file)
word_count, unique_word_count = word_count(file)

print('Total word count:  {}\n'.format(word_count) + 
    'Unique words:  {}\n'.format(unique_word_count) + 
'Sentences:  {}'.format(sentence_count))

输出如下:

Total word count:  0
Unique words:  0
Sentences:  5

真正奇怪的是,如果我注释掉sentence_count()函数,word_count()函数就会开始工作并输出正确的数字。

为什么会出现这种不一致?如果我注释掉任何一个函数,一个将输出正确的值,而另一个将输出 0。有人可以帮助我使这两个功能都起作用吗?

标签: pythonregex

解决方案


问题是您只能遍历打开的文件一次。您需要重新打开或倒回文件以再次对其进行迭代。

例如:

with open('sample.txt', 'r') as f:
  sentence, sentence_count = sentence_count(f)
with open('sample.txt', 'r') as f:
  word_count, unique_word_count = word_count(f)

或者,f.seek(0)将倒带文件。


推荐阅读