首页 > 解决方案 > 使用索引查找和打印特定单词

问题描述

我有一个关于我坚持的编码问题的问题。

我要做的是获取用户指定的索引列表,然后运行文件并在这些特定索引处打印单词。

这是我到目前为止的代码:

# get a hold of the local module url for web support
import url

# define repository for text files of interest
TEXT_REPOSITORY = "http://www.cs.virginia.edu/~cs1112/text/"

# input name of web file
file_name = input("Enter name of web file: ")

# define the link to the web file -- TEXT_REPOSITORY + name of the web file
link = TEXT_REPOSITORY + file_name

# get the text contents of the date file using url function get_contents()
text = url.get_contents(link)

# split text into a list of words
words = text.split()

# input indices of interest
reply = input("Enter indices of interest: ")

# split indices reply into a list of numeric strings
nstrings = reply.split()

# produce a list of numeric indices from the numeric strings
indices = []
for ns in nstrings:
    indices.append(int(ns))

# run through the indices and print the associated word from words
for i in indices:
    ...

我被困在最后一步,实际上是使用索引来搜索和打印指定的单词。我想要做的是使用 for 循环在页面(我已经导入并转换为字符串列表)中搜索指定索引处的单词并按该顺序打印它们。

理想情况下,完成的运行看起来像这样:

Enter name of web file: macaronic.txt

Enter indices of interest: 8 3 2 6 4 1 0 9 5 7

 

macaronic

denotes

a

mixture

of

words

drawn

from

different

languages

如何解决?

标签: pythonurlindexing

解决方案


推荐阅读