我正在编写一个用户将输入句子(没有标点符号)的任务,程序会将这些单词存储在列表中,然后将每个单词替换为创建的列表中单词的位置。 关于如何处理这个问题我没有太多想法,因为我是python的新手,但是我假设我应该首先将这些单词存储在Excel数据库中,然后将它们放在列表中。 如果我能得到一些帮助,我将非常感谢,谢谢。
有关该任务的详细信息,请查看此屏幕截图:Task Details
答案 0 :(得分:1)
这是一个如何做的快速示例。记住做自己的工作,仅用于学习。
sentence = input("Write a sentence: ")
sentence_array = sentence.lower().split(" ") # Split lowercased sentence to an array
individuals = [] # List for individual words
for x in range(0, len(sentence_array)): # Loop to find individual words
if sentence_array[x] not in individuals: # If word is not picked already...
individuals.append(sentence_array[x]) # ...append it to individuals list
positions = [] # List that contains positions of the words
for x in range(0, len(sentence_array)): # Loop to append positions to a list
positions.append(individuals.index(sentence_array[x]) + 1) # Appending indexes of words, notice +1
with open("Result file.txt", "w") as f: # Write results to a file
for x in range(0, len(positions)): # Loop to write indexes
if x == len(positions)-1: # If last position, write line break instead of comma
f.write("%s\n" % positions[x])
else:
f.write("%s," % positions[x])
for y in range(0, len(individuals)): # Loop to write words
if y == len(individuals)-1: # If last word, write line break instead of comma
f.write("%s\n" % individuals[y])
else:
f.write("%s, " % individuals[y])
可以在Result file.txt
中查看输出答案 1 :(得分:0)
您应该展示一些努力并就代码提出更具体的问题。 这是一个使用numpy数组的简短解决方案:
#ask for sentence, split the words by space and put the words in an array
sentence = np.array(raw_input("Enter a sentence: ").split(' '))
#find unique words and save their indices in the array/sentence (np.unique does not keep the order)
unique_words, index = np.unique(sentence, return_index = True)
#get unique words in sorted order by sorting the indices
unique_sorted = sentence[np.sort(index)]
#loop through sentence and return indices of the words in sorted unique words
result = [np.where(unique_sorted == word)[0][0] for word in sentence]
请注意,输出将移1,因为python索引从0开始:
>>> sentence = np.array(raw_input("Enter a sentence: ").split(' '))
Enter a sentence: ask not what your country can do for you ask what you can do for your country
>>> result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 2, 8, 5, 6, 7, 3, 4]
使用数组和东西可能会太复杂,这就是为什么你应该尝试与列表不同的东西。但是你得到了基本的想法:
获取您的输入,拆分
按排序顺序查找唯一字词
对于句子中的每个单词,在排序数据中查找索引