从索引词列表中重新创建句子

2024-04-26 04:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想怎么重现这个句子时有点困难:

“相信我,相信你!”

(对于那些看过古伦·拉甘的人来说有点畏缩……)使用我通过列举单词列表获得的索引:

[‘相信’、‘在’、‘我’、‘那个’、‘相信’、‘你’]

这个列表是.split()和.lower(),用于删除我以前编写的代码中的标点符号,以使单词列表文件和索引列表文件。 编制索引时,这些词以枚举形式出现:

(1,“相信”) (2,'英寸') (3,‘the’) (4,“我”) (5,“那个”) (6,“相信”) (7,'你')

这就是我所拥有的,因为我一直在寻找一个解决方案,其中没有一个为我的代码工作。到目前为止,事情是这样的:

with open("Words list file 2.txt", 'r') as File:
    contain = File.read()
    contain = contain.replace("[", "")
    contain = contain.replace("]", "")
    contain = contain.replace(",", "")
    contain = contain.replace("'", "")
    contain = contain.split()
print("The orginal file reads:")#prints to tell the user the orginal file
print(contain)

for i in enumerate(contain, start = 1):
    print(i)

Tags: 文件the代码列表单词lowerreplace句子
2条回答

您可以使用join方法连接列表中的字符串,如下所示:

my_list = ['believe', 'in', 'the', 'me', 'that', 'believes', 'you']
>>> ' '.join(my_list)
'believe in the me that believes you'
#                                ^ missing "in"

但这将导致在"believes"之后缺少"in"的字符串。如果您希望根据上一个列表中的单词索引生成新字符串,可以使用临时列表存储索引,然后在生成器表达式上执行join,如下所示:

>>> temp_list = [0, 1, 2, 3, 4, 5, 1, 6]
>>> ' '.join(my_list[i] for i in temp_list)
'believe in the me that believes in you'
' '.join(['believe', 'in', 'the', 'me', 'that', 'believes', 'you'])

不确定原始文件包含什么或从文件加载时“contains”变量是什么。请出示那个。你知道吗

相关问题 更多 >