簡體   English   中英

將列表值分配給字典 python

[英]assign list values to dictionary python

所以我正在使用一組由以下內容組成的字典

{'Summery':["00","01","02"],'Location':["03","04"],'Name':["05"]}

現在每個數字都與每行的字數相關

在我擁有的文本文件中,格式化的行

Fun Reading Afterschool 50°N 50°E Library
Education Learning Study 51°N 51°E School
Exercise Play Social 52°N 52°E Playground

如何將 input.txt 轉換為所需的輸出:

輸出.txt

{'Summery':["Fun","Reading","Aftershchool"],'Location':["50°N","50°E"],'Name':["Library"]}
{'Summery':["Education","Learning","Study"],'Location':["51°N","51°E"],'Name':["School"]}
{'Summery':["Exercise","Play","Social"],'Location':["52°N","52°E"],'Name':["Playground"]}

到目前為止我有

file = open("input.txt", 'r')
lines = file.readlines()

list_word = []
for l in lines:
    list_word.append(l.split(" "))

my_list = [line.split(' , ')for line in open ("test")]

string1="".join(map(str,my_list))
print(string1)

new_main = open("output.txt", 'w')
new_main.write(string1)
new_main.close()

打印並創建 output.txt

['Fun Reading Afterschool 50°N 50°E Library\n']['Education Learning Study 51°N 51°E School\n']['Exercise Play Social 52°N 52°E Playground']

假設摘要總是 3 個單詞,位置 2 和名稱 1 個單詞(每個單詞由一個空格分隔),您可以根據它們的索引獲取想要的單詞。

for string in string1:
    splits = string.split(" ")
    
    summary = splits[0:3]
    location = splits[3:5]
    name = splits[5:6]
    
    print(f"Summary: {summary}, location: {location}, name: {name}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM