You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:30:49