我正在尝试使用 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/