所以我需要將一個txt檔案拆分成字典。txt 檔案可能如下所示:
Keyone -2
key-two 1
Key'Three -3
Key four-here 5
我想我需要檢查反向串列以檢查倒數第二個元素是“”還是“-”,但由于字串中的單詞之間可能有“-”,我有點困惑至于如何解決這個問題。
我需要字典看起來像 [str(key); 整數(值)]
到目前為止,我的嘗試看起來像:
`
for line in file
a=line.split()
value = a[-1]
key=line[0:-2]
key=key.replace("-","")
`
uj5u.com熱心網友回復:
試試下面的代碼:
# Define input
txt = "Keyone -2\nkey-two 1\nKey'Three -3\nKey four-here 5"
print(txt)
# Split the text by newlines
lines = txt.split('\n')
print(lines)
# Iterate over all lines
d = {}
for line in lines:
line.split(' ')
# The key is element after the last space
key = "".join(line[:-1])
# The value is everything before the first space
value = line[-1]
# Assuming it can only be an integer
value = int(value)
d[key] = value
print(d)
uj5u.com熱心網友回復:
with open ("text.txt") as f:
for i in f:
a=i.split()
value=a[-1]
key=i[0:-2]
#print(type(key))
key=key.replace("-","")
d[key[0:-1]]=value
print(d)
uj5u.com熱心網友回復:
以下是使用正則運算式的答案:
import re
data_to_parse = """
Keyone -2
key-two 1
Key'Three -3
Key four-here 5
"""
data_to_parse = data_to_parse.splitlines()
pattern = " -?\d"
new = {}
for line in data_to_parse:
if re.findall(pattern, line):
x = re.findall(pattern, line)
#print(line[line.find(x[0]) - 1:])
new[line[:line.find(x[0])].strip()] = line[line.find(x[0]):].strip()
print(new)
查看輸出:

編輯:
如果值需要是整數,請按以下方式更改該行:
new[line[:line.find(x[0])].strip()] = int(line[line.find(x[0]):].strip())
所以輸出將如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471988.html
