如何用Python在文本文件中查找指定单词并输出其所在行
读取文本文件并输出指定单词所在行
假设我们有一个名为example.txt的文本文件,内容如下:
steve 22 london john 30 paris alex 19 berlin
需求是查找指定单词(比如john),并输出该单词所在的整行内容,最终输出:
john 30 paris
以下是几种实现方案:
Python 实现
包含匹配(行中出现目标字符串即匹配)
target_word = "john" file_path = "example.txt" with open(file_path, 'r') as file: for line in file: cleaned_line = line.strip() if cleaned_line and target_word in cleaned_line: print(cleaned_line)
精确单词匹配(仅匹配独立单词,避免误匹配johnny这类包含目标的字符串)
target_word = "john" file_path = "example.txt" with open(file_path, 'r') as file: for line in file: cleaned_line = line.strip() if cleaned_line and target_word in cleaned_line.split(): print(cleaned_line)
Shell 命令实现
包含匹配
grep "john" example.txt
精确单词匹配
grep -w "john" example.txt
内容的提问来源于stack exchange,提问作者Evan John
相关产品推荐
相关产品推荐

