python中交换两个列表元素的位置_在python中交换两个列表之间的列表项?

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

例如:

第一行,两列单词中的一列:['We,'You']。在

String:“我们和我们的猫去参加了婚礼”

输出:“你和你的猫去参加了婚礼”

给定的txt文件包含两列,所以在写了一段代码后,我设法将单词分成若干列表,有一个名为“old_word_list”的列表,其中包含字符串中所有单词的单个字符串,以及一个名为“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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值