[英]Append Dictionary or list of values at the end of each row in csv using python
[英]Append each input word position and row values to dictionary using python
我们有一个文件中的数据。 我们必须读取文件中的数据并构建一个字典,例如以每个字母为键,值将是文件中字母的行号和列号。有人可以帮我吗?
文件数据:
"hi how are you"
"hi hello"
示例输出:
{'h':[(1,1),(1,3),(2,1),(2,3)],
'i':[(1,2),(2,1)],
....}
下面给出我的代码:
def read_text():
d={}
with open('C:\Users\Desktop\sampletext.txt','r') as g:
ff=g.readlines()
ff = map(lambda s: s.strip(), ff)
print(ff,"ffff")
row=1
for line in ff:
list1=[]
li = line.split(" ")
for w in li:
for k in w:
pos = line.index(k)
d[k]=(row,pos)
#how to append list of values(i.e pos and index) to dict key
row +=1
print(d,"dd")
使用line.index
不是一个好主意,因为 (a) 您必须多次扫描同一行,并且 (b) 您将始终只获得该行中该字符的第一个位置。 此外,循环中的d[k]=(row,pos)
意味着您在每次迭代中用该单个位置替换位置列表。
相反,您可以只使用enumerate
来迭代行和字符及其索引。
from collections import defaultdict
text = "hi how are you\nhi hello"
d = defaultdict(list)
for i, line in enumerate(text.splitlines()):
for j, c in enumerate(line):
d[c].append((i,j))
(此处使用defaultdict
,但您也可以使用普通dict
并使用空列表初始化每个字符。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.