如何使用文件处理从python中显示单词

如何使用文件处理从python中显示单词,python,python-3.x,Python,Python 3.x,问题: 编写用于读取words.txt的Python程序单击此处。每次用户按ENTER键时,显示此文件中的随机单词。确保显示随机行号,后跟相应的单词。请注意,在本例中,每行包含一个单词 我试过的 输出 无输出只需将文本文件的完整路径与文本文件的openrentire路径对齐,即“r”作为文件: 它应该可以工作,否则您打开的文本文件会出现问题。此程序工作正常。但是为了打印问题陈述中给出的行号,我修改了这段代码 import random # Open the file in read mode

问题:

编写用于读取words.txt的Python程序单击此处。每次用户按ENTER键时,显示此文件中的随机单词。确保显示随机行号,后跟相应的单词。请注意,在本例中,每行包含一个单词

我试过的

输出


无输出

只需将文本文件的完整路径与文本文件的openrentire路径对齐,即“r”作为文件:


它应该可以工作,否则您打开的文本文件会出现问题。

此程序工作正常。但是为了打印问题陈述中给出的行号,我修改了这段代码

import random 
# Open the file in read mode 
i=0
line_no=0

with open("test.txt", "r") as file: 

    allText = file.read() 
    words = list(map(str, allText.split())) 
    # print random string 
    x=random.choice(words)
    #find the selected word's index using for loop
    for i in range(len(words)):
        if words[i]==x:
            line_no=i+1
    #print the output       
    print("Line number :{} \nWord :{}".format(line_no,x))
    

你能提供一些示例输入吗?它适用于我的测试文件。@supersormer:我如何读取联机编译器中的文件???查找一些已经完成文件读取的示例。很抱歉坚持,我只是想了解您的请求。您要求每次用户按ENTER键时显示此文件中的随机单词,在我看来,答案是-2是唯一符合此标准的。提前谢谢
import random 
# Open the file in read mode 

with open("MyFile.txt", "r") as file:
    allText = file.read()
    words = list(map(str, allText.split())) 
    len_ = len(words)
    while True:
        _ = input()
        i = random.randrange(len_)
        print(i, words[i])


import random 
# Open the file in read mode 
i=0
line_no=0

with open("test.txt", "r") as file: 

    allText = file.read() 
    words = list(map(str, allText.split())) 
    # print random string 
    x=random.choice(words)
    #find the selected word's index using for loop
    for i in range(len(words)):
        if words[i]==x:
            line_no=i+1
    #print the output       
    print("Line number :{} \nWord :{}".format(line_no,x))