基于Python实现TXT文件单词提取及指定词后邻词提取技术问询
Python从TXT提取单词及指定序列后单词的实现方案
嘿,我来帮你搞定这两个文本处理的问题,直接上实用的代码和思路!
1. 如何使用Python从TXT文件中提取单词
提取单词的核心是先读取文件内容,再把文本拆分成独立的单词。这里分两种场景处理:
场景一:无复杂标点的纯空格分隔文本
如果你的TXT文件里只有空格分隔的单词,没有逗号、句号这类标点,直接用split()方法就能快速拆分:
# 读取文件内容 with open('Test.txt', 'r', encoding='utf-8') as f: content = f.read() # 拆分出所有单词 words_list = content.split() print(words_list)
场景二:带标点的常规文本
如果文本里有标点符号(比如句子末尾的句号、逗号),推荐用正则表达式精准提取单词,避免把标点也算进单词里:
import re with open('Test.txt', 'r', encoding='utf-8') as f: content = f.read() # 提取所有由字母、数字、下划线组成的单词 words_list = re.findall(r'\b\w+\b', content) print(words_list)
这里\b表示单词边界,\w+匹配一个或多个字母、数字或下划线,能完美过滤掉标点符号。
2. 搜索指定单词序列并提取紧随其后的单词
针对你给出的示例需求(提取所有test后面的单词),可以通过遍历单词列表实现,直接上适配的代码:
import re # 第一步:读取并提取文本中的单词 with open('Test.txt', 'r', encoding='utf-8') as f: content = f.read() words_list = re.findall(r'\b\w+\b', content) # 第二步:查找'test'后面的单词 target_word = 'test' result_words = [] for idx in range(len(words_list)): # 找到目标单词后,确保后面还有单词再提取 if words_list[idx] == target_word and idx + 1 < len(words_list): result_words.append(words_list[idx+1]) print(result_words) # 输出正好是你要的:['to', 'the', 'environ_ment']
如果需要匹配多单词组成的序列(比如找is a test后面的单词),也可以调整逻辑,检查连续单词是否匹配目标序列:
# 示例:查找序列['is', 'a', 'test']后面的单词 target_sequence = ['is', 'a', 'test'] seq_len = len(target_sequence) result_words = [] for idx in range(len(words_list) - seq_len): # 检查当前位置开始的连续单词是否匹配目标序列 if words_list[idx:idx+seq_len] == target_sequence: if idx + seq_len < len(words_list): result_words.append(words_list[idx+seq_len]) print(result_words) # 针对你的示例文本,输出:['to']
内容的提问来源于stack exchange,提问作者Lee Murray




