[英]How to find specific word in text file using python
我有一个包含我们的文本文件,uss,usr想读取特定单词和单词“ uss”的长度如何使用python进行读取
import re
def findwords(text, length):
return re.findall(r"\b\w{{{0}}}\b".format(length), text)
\\b
is a word boundary that ensures only entire words are matched. \\b
是一个单词边界,可确保仅匹配整个单词。
r"\\w{{{0}}}".format(3)
results in r"\\w{3}"
. r"\\w{{{0}}}".format(3)
产生r"\\w{3}"
。 The double braces are necessary for escaping. 双括号是逃脱所必需的。
\\w
matches alphanumeric characters; \\w
匹配字母数字字符; if you want to avoid matching digits or the underscore with it, use [^\\W\\d_]
in its place: 如果要避免匹配数字或下划线,请在其位置使用[^\\W\\d_]
:
def findwords(text, length):
return re.findall(r"\b[^\W\d_]{{{0}}}\b".format(length), text)
Why not use regex ? 为什么不使用正则表达式?
import re
help(re)
http://docs.python.org/library/re.html http://docs.python.org/library/re.html
For your trouble, you can use following regex : 麻烦的是,您可以使用以下正则表达式:
- r'\\w{3}'
: match 3 characters (no digit) r'\\w{3}'
:匹配3个字符(无数字)
You can add \\s
before or after for match space or tabs. 您可以在匹配空间或制表符之前或之后添加\\s
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.