将列表中的单词及其位置写入文件

时间:2016-11-03 18:53:44

标签: python list file

我在学校被分配了一项任务(我会复制粘贴细节,因为它会比我更好地解释它)

  

开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。

例如,句子

ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY

包含单词ASK,NOT,WHAT,YOUR,COUNTRY,CAN,DO,FOR,YOU 可以使用序列

从该列表中的这些单词的位置重新创建该句子
1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5

将单词列表和这些单词在句子中的位置保存为单独的文件或单个文件。

  

分析该系统的要求,并设计,开发,测试和评估程序:

     
      
  • 识别句子中的单个单词并将其存储在列表中
  •   
  • 为该列表中的字词创建一个位置列表
  •   
  • 将这些列表保存为单个文件或单独文件。
  •   

_

到目前为止,我已经能够将文字写入文件而不是数字 - 我只得到数字1-非常欢迎任何帮助:)

 words=['ASK','NOT','WHAT','YOUR','COUNTRY','CAN','DO','FOR','YOU','ASK','WHAT','YOU','CAN','DO','FOR','YOUR','COUNTRY'] 
    word_raw = ['ASK','NOT','WHAT','YOUR','COUNTRY','CAN','DO','FOR','YOU']
    numbers = ['']
    if 'ASK' in words:
        numbers.append('0')
        numbers.append('9')

    if 'NOT' in words:
        numbers.append('1')

    if 'WHAT' in words:
        numbers.append('2')
        numbers.append('10')

    if 'YOUR' in words:
        numbers.append('3')
        numbers.append('15')

    if 'COUNTRY' in words:
        numbers.append('4')
        numbers.append('16')

    if 'CAN' in words:
        numbers.append('5')
        numbers.append('12')

    if 'DO' in words:
        numbers.append('6')
        numbers.append('13')

    if 'FOR' in words:
        numbers.append('7')
        numbers.append('15')
    if 'YOU' in words:
        numbers.append('8')
        numbers.append('11')

        print (numbers)
    for x in range(len(words)):
        MyFile = open('Task2File.txt', 'w')   
        with open("Task2File.txt", mode="w",encoding="utf-8") as my_file:
              for words in word_raw:
                   my_file.write(words+"\n")                                                             
    for x in range(len(numbers)):
        MyFile = open('Task2FileNumbers.txt', 'w')   
        with open("Task2FileNumbers.txt", mode="w",encoding="utf-8") as my_file:
              for numbers in numbers:
                   my_file.write(numbers+"\n")
                   print (numbers)

2 个答案:

答案 0 :(得分:0)

这是词典最擅长的事情之一。

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
words = sentence.split()
word_num = 1
word_dict = {}
output = []
for word in words:
    if word not in word_dict:
        word_dict[word] = word_num
        word_num += 1
    output.append(word_dict[word])
print(output)

将列表编写为单个文件可能最容易,以确保它们的顺序相同。

with open('output.txt', 'w+') as f:
     f.writelines(' '.join([key, str(value), '\n']) 
                  for key, value in sorted(word_dict.items(), key=lambda x: x[1]))

答案 1 :(得分:0)

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
words = sentence.split()
d = {w: words.index(w) + 1 for w in set(words)}
output = [d[word] for word in words]
print(output)