簡體   English   中英

Python將文本文件讀入字典,字符串列表

[英]Python read text file into dictionary, list of strings

我正在嘗試將文本文件讀入字典。 文本文件包含一個人的名字,網絡和朋友的名字。 字典的密鑰是人的名字,值是該人的網絡,這是文本文件:

Pritchett, Mitchell\n
Law Association\n
Dunphy, Claire\n
Tucker, Cameron\n
Dunphy, Luke\n
\n\n
Tucker, Cameron\n
Clown School\n
Wizard of Oz Fan Club\n
Pritchett, Mitchell\n
Pritchett, Gloria\n
\n\n
Dunphy, Alex\n
Orchestra\n
Chess Club\n
Dunphy, Luke\n

這是我所做的

def person_to_networks(file):

我在lst [0]中的'if“ \\ n”和“,”行出現錯誤。 它說列表索引超出范圍。 請幫我。 我不知道這段代碼出了什么問題。

因為第一次通過循環,所以您嘗試在lst仍為[]時訪問lst [0]。

至少第一行,lst是空列表( [] )。 您應該先將一些值附加到lst。


可能您想執行以下操作:

if "\\n" and "," in lst[0]: if "\\n" and "," in line[0]:

elif "," not in lst[1:]:elif "," not in line[1:]:

最后一行中的new_person_friends未定義。 您需要解決此問題。


當line為“ \\ n”時,lst將在networks更新后清除。
並且您的數據具有“ \\ n \\ n”。 這意味着2個連續的空行。 在第二個“ \\ n”中,lst是空列表,因為已處理了第一個“ \\ n”。
您需要修復代碼來避免此類問題: if line == '\\n' and lst != []:

您會收到該錯誤,因為您將lst初始化為空[],然后檢查了不存在的第一個元素。

您說要將文件轉換為字典,我建議使用以下簡單代碼:

import re  # import regex library
# open the file and import your data
f = open('data', 'r')
data = f.read()
f.close()
# initialize your data to be processed
dict = {}
data = data.replace('\\n', '') # remove \n characters
data = data.split('\n\n')      # split it into blocks
for block in data:
    block = block.split('\n')  # split each bock into lines
    nets = []
    for line in block:
        if ',' not in line and line != '': # find networks
            nets.append(line)
    block[0] = re.sub(r'(\w+),\s(\w+)', r'\2, \1', block[0])  # ADDED to switch first name and last name
    dict.update({block[0]: nets})   # update the result dictionary
print dict

這將為您建議的文件示例提供以下結果:

{'Pritchett, Mitchell': ['Law Association'], 'Tucker, Cameron': ['Clown School', 'Wizard of Oz Fan Club'], 'Dunphy, Alex': ['Orchestra', 'Chess Club']}

如果這不是您想要的,請更詳細地描述它是什么。

編輯:為了切換first namelast name您可以在更新字典之前僅添加該行以進行切換。 我在上面的代碼中添加了該行,它使用了正則表達式( 別忘了像在我的代碼開頭一樣添加“ import re” ):

'(\w+),\s(\w+)' # used to find the first name and last name and store them in \1 and \2 match groups.
'\2, \1'        # to replace the place of the match groups as required.
 OR '\2 \1'     # if you don't want the comma 

但是和你喜歡的,你可以操縱它,例如:你可以刪除,或者類似的東西。

切換后的輸出將變為:

{'Alex, Dunphy': ['Orchestra', 'Chess Club'], 'Cameron, Tucker': ['Clown School', 'Wizard of Oz Fan Club'], 'Mitchell, Pritchett': ['Law Association']}

編輯:另一種方式向之間切換firstlast名稱( 去掉“再進口”和先前添加的線,並與這三條線使用相同的縮進替換 ):

s = block[0].split(', ')
s.reverse()
block[0] = ', '.join(s)  # or use ' '.join(s) if you don't want the comma

希望這可以幫助。

暫無
暫無

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

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