如何使用python在文本文件中查找特定单词

时间:2012-09-29 05:29:10

标签: python

我有一个包含我们的文本文件,uss,ussr想要读取特定单词和单词“uss”的长度如何使用python读取

2 个答案:

答案 0 :(得分:2)

import re
def findwords(text, length):
    return re.findall(r"\b\w{{{0}}}\b".format(length), text)

\b是一个单词边界,可确保只匹配整个单词。

r"\w{{{0}}}".format(3)会产生r"\w{3}"。双括号是逃跑所必需的。

\w匹配字母数字字符;如果您想避免匹配数字或下划线,请在其位置使用[^\W\d_]

def findwords(text, length):
    return re.findall(r"\b[^\W\d_]{{{0}}}\b".format(length), text)

答案 1 :(得分:0)

为什么不使用正则表达式?

import re
help(re)

http://docs.python.org/library/re.html

为了您的麻烦,您可以使用以下正则表达式:
  - r'\w{3}':匹配3个字符(无数字)

您可以在匹配空格或标签之前或之后添加\s

相关问题