Python:我在获取文本文件并显示找到单词的行号时遇到问题

Posted

技术标签:

【中文标题】Python:我在获取文本文件并显示找到单词的行号时遇到问题【英文标题】:Python: I'm having trouble taking a text file and displaying which line number a word is found 【发布时间】:2016-02-08 20:18:54 【问题描述】:

所以我有一个文本文件,它是一首诗,所以有行,我希望它设置在用户输入单词的地方,程序会打印找到该单词的行。这就是我所拥有的。我不明白为什么它不起作用。

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 个字符开始。

基本上我有这个: 数据 = f.read() / 打印(data.index(word))

任何建议都会很棒!

【问题讨论】:

【参考方案1】:

循环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)

但是,这仍然有一个错误。如果您正在搜索apple,它也会匹配applesauce。尝试将其作为练习来解决:)

【讨论】:

这表示诗的每一行都有这个词,但事实并非如此【参考方案2】:

为了回答您最初提出的问题,

...程序打印找到单词的行

您想要执行以下操作

获取用户输入(单词和诗歌文件)

打开包含这首诗的文件

将内容读入枚举诗行列表

对于每一行,如果有用户的话,打印行号和 线


脚本

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, 

【讨论】:

我建议跳过将文件读入列表(with 行之后的行)并将for 行更改为:for i, line in enumerate(file, start=1):enumeratestart=1 参数将使行号从 1 而不是 0 开始。【参考方案3】:

这是一个类似于你的代码的答案:

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)))

【讨论】:

以上是关于Python:我在获取文本文件并显示找到单词的行号时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章

如何将文件中的不同行号存储到一个集合中?

通过 sqlite 根据特定条件获取行号

用 sed 替换文件中最后出现的文本

如何使用 PHP 在文本文件中搜索字符串

如何在目标c中的多个标签上显示文本文件中的随机单词

如何在文本文件中查找行并导出行号