在Python 3.6中,如何显示文本文件中出现单词的哪些行?

时间:2018-04-20 17:02:14

标签: python python-3.x

因此,假设您有一个名为select * from products where shape_id = (select id from shapes where shape = 'round') and color_id = (select id from colors where color = 'red') and height_id = (select id from heights where height = 'tall') and weight_id = (select id from weights where weight = 'heavy'; 的文本文件,它包含四个句子,每个句子位于不同的行。

这是一个粗略的例子

myfile.txt

如何在python中进行编码,在新的文本文件中显示每个单词及其所在的相应行?

示例输出

Hello I like the color red

Red is a primary color

I do not like blue

I like orange as well

我目前的代码

Hello 1

I 1 3

like 1 3

the 1

color 1 2

red 1 2

is 2

a 2

primary 2

do 3

not 3

blue 3

orange 4

as 4

well 4

1 个答案:

答案 0 :(得分:0)

此程序的行为应符合您的要求:

with open("test.txt",'r+') as f:
    # Read the file 
    lines=f.readlines()

    # Gets the word
    word=input("Enter the word:")

    print(word+" occured on line(s):",end=' ')

    # Puts a flag to see if the word occurs or not
    flag=False

    for i in range(0,len(lines)):
        # Creates a list of words which occured on the line
        words=lines[i].split(' ')

        # Checks if the word exists or not
        if words.count(word)>0 or words.count(word+"\n"):
            # Flag will be true since the word occured
            flag=True
            print(i+1 , end=' ')
    if not flag:
        print("It didn't occur.")
    else:
        # An empty line 
        print("")