如何解决如何在文本文件中搜索单词并使用Python打印整行?
我正确的代码:
with open("text.txt") as openfile:
for line in openfile:
for part in line.split():
if "Hello" in part:
print(part)
只能在打印的文本中找到像hello这样的特定单词。 问题是,我希望它停止仅打印该单词,并打印其中包含该单词的整行。 我该怎么办?
这是我现在得到的结果:
hello
hello
hello
请注意,文本文档包括:
hello,i am a code
hello,i am a coder
hello,i am a virus
解决方法
您只需要执行非必需的循环,请尝试以下操作:
with open("text.txt") as openfile:
for line in openfile:
if "Hello" in line:
print(line)
,
请注意,在您的示例中,单词“ hello”是LowerCase,因此,为了同时捕获大写和小写字母,我建议使用这段经过修改的代码:
with open("text.txt") as openfile:
for line in openfile:
if "hello" in line.lower():
print(line)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。