[英]Python: I'm having trouble taking a text file and displaying which line number a word is found
所以我有一个文本文件,它是一首诗,所以有线条,我希望它设置在用户输入单词的位置,程序打印出找到单词的哪一行。 这就是我所拥有的。 我不明白为什么它不起作用。
f=open(file,'r')
word = input('enter word: ')
data = f.read()
x= data.split('\n')
count = 0
while word in x[count]:
print(word,'is on line'count)
count += 1
我觉得应该发生一些事情,但事实并非如此。 有什么建议?
另外,我还想显示找到这个单词的哪一个(第一个)字符? 我有一个大致的想法,但我无法弄清楚如何相对于线显示它。 它显示相对于整个文本。 所以它会显示'字符200'而不是'字符5',因为对于它所在的行,它从第5个字符开始。
基本上我有这个:data = f.read()/ print(data.index(word))
任何建议都会很精彩!
while word in x[count]
循环终止于单词不在行的第一行。
尝试这样的事情:
word = input('enter word: ')
with open(file) as f: data = f.read()
lines = data.split('\n')
count = 0
for linenr, line in enumerate(lines):
print(word, "is on line", linenr)
if word in line:
count += 1
print(count)
但是,这还有一个bug。 如果你正在寻找apple
,它也会匹配applesauce
。 尝试修复它作为练习:)
要回答您最初陈述的问题,
...程序会打印出找到该单词的行
您想要执行以下操作
获取用户输入(单词和诗的文件)
打开包含诗歌的文件
将内容读入诗歌行的枚举列表中
对于每一行,如果它有用户的单词,则打印行号和行
脚本
from sys import argv
word = argv[1]
poem = argv[2]
with open(poem) as file:
lines = file.read().split('\n')
for i, line in enumerate(lines):
if word in line:
print i, line
示例文件
God and the Soldier, we adore,
In time of danger, not before.
The danger passed and all things righted,
God is forgotten and the Soldier slighted.
跑
> python poemscript.py danger poem.txt
1 In time of danger, not before.
2 The danger passed and all things righted,
这是一个类似于您的代码的答案:
word = input('enter word: ')
with open(filename) as fobj:
for line_no, line in enumerate(fobj, start=1):
if word in line:
print('"{word}" is on line {line_no} at column {char_pos}'.format(
word=word, line_no=line_no, char_pos=line.index(word)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.