在python中交换两个列表之间的列表项?

时间:2012-04-11 10:58:01

标签: python string

我有一条评估要求我在列表中交换单词。我给出了一个txt文件,其中包含一列单词“旧单词”和一列单词“新单词”。我需要定义一个函数,检查字符串以查看“旧单词”列表/列中的单词是否在字符串中,然后我需要将该单词与对应的单词交换'新词'专栏。

例如:

两列单词中的第一行:['我们,'你']。

字符串:“我们和我们的猫去参加婚礼”    输出:'你和猫一起去参加婚礼'

给出的txt文件包含两列,因此在写完一些代码后,我设法将这些单词拆分成某些列表,有一个名为“old_word_list”的列表,其中包含所有单词的单个字符串。可以在字符串中,以及一个名为“new_word_list”的列表,其中包含用于替换旧单词的单词。

伪代码概念: 如果string包含来自old_word_list的任何单词/ s,则将word / s替换为相同(对应)索引中new_word_list中的单词。

这是评估的唯一部分,如果有人可以帮助我,我将会非常感激,如果我遗漏了任何需要的信息,请评论。谢谢。

完整代码:

# Declaring a global variables for the file, so it can be used in the code.
filename = "reflection.txt"
the_file = open(filename)

# Declaring any other reqiured variables.
word_list = []
old_word_list = []
new_word_list = []

# Creating loop to add all words to a list. 
for line in the_file:

    # Appends each line to the end of the list declared above. In appending
    # the lines, the code also removes the last character on each line (/n).
    word_list.append(line[:-1])

# Creating a loop to split each individual word, then appends the
# old/original words to a declared list, and appends the new words
# to a declared list.
for index in range(len(word_list)):
    temp_word = word_list[index]
    split_words = temp_word.split()
    old_word_list.append(split_words[0])
    new_word_list.append(split_words[1])

# Defining a function to produce altered statement.
def reflect_statement(statement):

    # Swaps the old word with the new word.
    for i in range(len(old_word_list)):
        if old_word_list[i] in statement:
             statement.replace(old_word_list[i], new_word_list[i])

    # Replaces '.' and '!' with '?'    
    for index in range(list_length):
        if old_word_list[index] in statement:
            statment = statement.replace(old_word_list[index], \
                                         new_word_list[index])

    statement = statement.replace(".", "?")
    statement = statement.replace("!", "?")

    # Returns result statement.
    return statement.

5 个答案:

答案 0 :(得分:3)

您可以使用此代码:

# the words to be replaced
old_word_list=['We','cat']

# the new words
new_word_list=['You','dog']

my_string="We went to a wedding with our cat"

# it prints "We went to a wedding with our cat"
print my_string

# iterate over the list of old words
for word in old_word_list:
  # get the index of the current word
  index = old_word_list.index(word)

  # use this index to do the replacement with the words of the two lists
  my_string = my_string.replace(old_word_list[index], new_word_list[index])

# it prints "You went to a wedding with our dog"
print my_string

根据作者的评论更新了答案:

# the words to be replaced
old_word_list=['We','cat']

# the new words
new_word_list=['You','dog']

def reflect_statement(statement):
  # iterate over the list of old words
  for word in old_word_list:
    # get the index of the current word
    index = old_word_list.index(word)

    # use this index to do the replacement with the words of the two lists
    statement = statement.replace(old_word_list[index], new_word_list[index])

  return statement

mystring="We went to a wedding with our cat"
mystring = reflect_statement(mystring)
print mystring

在作者最后添加源代码后更新了答案:

将您的功能更改为此功能:

def reflect_statement(statement, old_word_list, new_word_list):
  mystr=statement
  # iterate over the list of old words
  for word in old_word_list:
    # get the index of the current word
    index = old_word_list.index(word)

    # use this index to do the replacement with the words of the two lists
    mystr = mystr.replace(old_word_list[index], new_word_list[index])

  return mystr

答案 1 :(得分:1)

提示:

  1. "string string".split()#将空格上的字符串拆分为列表
  2. 您可以使用for循环遍历列表
  3. 列表有一个myList.index(element)来告诉您元素是否在列表中并返回其索引。
  4. 索引将在您的两个列表之间匹配(根据您的描述)
  5. 字符串也有一个“myString.replace(旧的,新的)”方法,以防你想要去那条路线。

答案 2 :(得分:0)

我将在发布答案之前说明我做出的一些假设,如果其中任何一个出错,请纠正我。

假设1:每列中的单词数量相同 假设2:每个单词都有一个,只有一个“伙伴”,一个单词对

在这种情况下,我会让每个单词对都成为一个列表。然后,为了继续你的伪代码,对于每一行文本,检查每个单词对并用单词[1]替换单词[0]。

EDIT 对不起只是发现我的措辞含糊不清。在制作单词对列表时,我也会将它们存储在列表中,例如[["old1", "new1"], ["old2", "new2"]]然后运行你的循环来替换它们(我现在不提供示例代码,因为我意识到你正在做一个任务,所以可能想要解决问题,但如果你在努力,请告诉我。)

答案 3 :(得分:0)

如果我理解你的话,可能就是这样,但它并不漂亮:

for i in range( len(old_word_list) )
    if old_word_list[i] in "some string":
         "some string".replace(old_word_list[i], new_word_list[i])

答案 4 :(得分:0)

# map old to new words (assuming there are no duplicates)
replacement_mapping = dict(zip(old_word_list, new_word_list))

# go through each word of the string, if it's in the mapping, use replacement, otherwise the word from the string
new_string = ' '.join([replacement_mapping.get(word, word) for word in given_string.split(' ')])