python - 使用正则表达式函数时返回值不一致
问题描述
我的代码表现得很奇怪,我感觉它与我正在使用的正则表达式有关。
我正在尝试确定文本文件中的总字数、唯一字数和句子数。
这是我的代码:
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。有人可以帮助我使这两个功能都起作用吗?
解决方案
问题是您只能遍历打开的文件一次。您需要重新打开或倒回文件以再次对其进行迭代。
例如:
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)
将倒带文件。
推荐阅读
- python - pandas 在 Datetime 上分组,格式为 mm.dd.yyyy
- gnuplot - 如何使这个 awk 脚本简单并以循环形式在 gnuscript 中使用
- python - 无法获取 Azure 认知服务的访问令牌(用于 tts)
- notepad++ - 如果至少有两个或多个大写字母我想将它们更改为小写
- regex - 在python中查找字符串中每个唯一字符的开始和结束索引
- javascript - 添加 javascript 后 prestashop 1.7.5.2 购物篮出现问题
- r - 在闪亮的应用程序中突出显示特定的直方图条
- c++ - 自定义类型(自己的类)的 std::rank 的实现
- java - 使用 MongoRepository 在 springBoot 中查询 MongoDb
- jquery - 在 Controller Asp.Net Mvc 和 Jquery Ajax 之间加密数据