python - 从文件中获取字数,忽略 python 中的注释行

标签 python algorithm file file-io io

我正在尝试使用 Python 计算文件中某个单词的出现次数。但我必须忽略文件中的注释。

我有这样一个函数:

def getWordCount(file_name, word):
  count = file_name.read().count(word)
  file_name.seek(0)
  return count

如何忽略以 # 开头的行?

我知道这可以通过逐行读取文件来完成,如 this question 中所述.有没有更快、更像 Python 的方式来做到这一点?

最佳答案

您可以使用正则表达式来过滤评论:

import re

text = """ This line contains a word. # empty
This line contains two: word word  # word
newline
# another word
"""

filtered = ''.join(re.split('#.*', text))
print(filtered)
#  This line contains a word. 
# This line contains two: word word  
# newline

print(text.count('word'))  # 5
print(filtered.count('word'))  # 3

只需将 text 替换为您的 file_name.read()

关于python - 从文件中获取字数,忽略 python 中的注释行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42626915/

相关文章:

python - 如何在 Pandas 中应用前一行结果

algorithm - 如何在 dijkstra 算法中以 O(log n ) 时间更新优先级队列中的 key ?

c++ - 在迭代期间哪个更快的并发队列 <> 与互斥队列 <>

java - 如何将行写入文件,并且每一行都是一个原子操作?

python - 双轴中缺少标签(matplotlib)

python - 是否可以运行所有单元测试?

python - json.dumps\u 将 unicode 转义为 utf8

algorithm - 为什么代码在 Codility 测试用例中返回负值?

java - 使用命令行参数将文件传递给程序

c++ - 输出文本文件的位置