简体   繁体   English

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

[英]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.

相关问题 如何使用python替换文本文件中某些特定单词的字符 - How to replace a character in some specific word in a text file using python 如何在Python中的文本文件中搜索特定单词 - How to search a text file for a specific word in Python Python正则表达式可在文本文件中间找到特定单词 - Python regex to find specific word in the middle of a text file 如何使用python在文本文件中查找单词的频率? 但用户应该给出输入词 - How to find the frequency of a word in a text file using python? But user should give the input word 如何打开文本文件并查找在一行中的特定单词和 append 文件名之后写入的内容到 Python 中的列表 - How to open a text file and find what is written after a specific word in a line and append that files name to a list in Python 我们可以使用python在docx文件中找到特定单词吗? - Can we find a specific word in a docx file using python? 如何在Python中的文本文件中查找特定的字符串 - How to find specific Strings in text file in Python 使用python查找文本文件中单词出现的第n个实例 - Find nth instance of occurrence of a word in a text file using python 如何使用 Python 在第二次出现特定单词后提取文本文件的一部分 - How to extract the part of a text file after the second occurrence of a specific word using Python 如何在python中的文本文件中删除特定单词之前的一行 - How to delete one line before a specific word in a text file in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM