我有两个文本文件,如
['i', 'hate', 'sausages', 'noa', 'hate', 'i']
然后是数字文件
1,2,3,3,2,1
现在我需要尝试将这两个文件相互加入
这是我到目前为止所拥有的
positionlist=open('positions.txt', 'r')#opening the code files with the postions
wordlist=open('Words.txt', 'r')#opening the word files
positions = positionslist.read() #the code is reading the file to see what it is in the txt and is saving them as a vairable
words = wordslist.read() #the code is reading the file to see what it is in the txt and is saving them as a vairable
print(positions) #prints the positions
print(words) #prints the words
positionfinal = list(positions) # makes the postions into a list
#this is where i need to tey and connect the two codes together
remover = words.replace("[","") #replacing the brackes withnothing so that it is red like a string
remover = remover.replace("]","")#replacing the brackes withnothing so that it is red like a string
答案 0 :(得分:0)
输入文件的格式看起来像是Python文字(字符串列表,整数元组),因此您可以使用ast.literal_eval
来解析它。然后,您可以使用内置的zip
函数将它们一起循环并打印出来。像这样:
import ast
with open('words.txt') as f:
words = ast.literal_eval(f.read()) # read as list of strings
with open('positions.txt') as f:
positions = ast.literal_eval(f.read()) # read as tuple of ints
for position, word in zip(positions, words):
print(position, word)
这是输出:
1 i
2 hate
3 sausages
3 noa
2 hate
1 i