Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:I';我在获取文本文件和显示找到单词的行号时遇到问题_Python_List_File_Text_Location - Fatal编程技术网

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

Python:I';我在获取文本文件和显示找到单词的行号时遇到问题,python,list,file,text,location,Python,List,File,Text,Location,所以我有一个文本文件,它是一首诗,所以有行,我希望它被设置在用户输入单词的地方,程序打印出找到单词的行。这是我的。我不明白为什么它不起作用 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 我觉得有些事情应该发生,

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

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
我觉得有些事情应该发生,但事实并非如此。有什么建议吗

另外,我还想显示该单词所在行中的哪个(第一个)字符?我有一个大致的想法,但我不知道如何相对于线显示它。它相对于整个文本显示。所以它会显示“character 200”而不是“character 5”,因为它所在的行从第5个字符开始

基本上我有: data=f.read()/ 打印(数据索引(word))


任何建议都很好

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

这意味着诗中的每一行都有这个词,但情况并非如此。我建议跳过将文件读入一个列表(带行的
之后的行),并将
行的
改为:
对于i,枚举(文件,开始=1)中的行:
enumerate
start=1
参数的行号从1开始,而不是从0开始。