【发布时间】:2018-09-17 10:18:48
【问题描述】:
我有一个函数,它返回一个列表,我在该列表中序列化为一个 json 对象并将其写入一个 JSON 文件。
结果是正确的,但问题是它返回了分隔列表中的每条记录。
我想要的是返回一个包含多个字典项的列表。
示例:
返回结果:
[{"file Name": "test1.txt", "searched Word": "th", "number of occurence": 1}][{"file Name": "test2.txt", "searched Word": "th", "number of occurence": 1}]
预期结果
[
{
"file Name": "test1.txt",
"searched Word": "th",
"number of occurence": 1
}
{
"file Name": "test2.txt",
"searched Word": "th",
"number of occurence": 1
}
]
我怎样才能做到这一点?
代码:
for counter, myLine in enumerate(textList):
thematch=re.sub(searchedSTR,RepX,myLine)
matches = re.findall(searchedSTR, myLine, re.MULTILINE | re.IGNORECASE)
if len(matches) > 0:
# add one record for the match (add one because line numbers start with 1)
d[matches[0]].append(counter + 1)
self.textEdit_PDFpreview.insertHtml(str(thematch))
'''
loop over the selected file and extract 3 values:
==> name of file
==> searched expression
==> number of occurence
'''
listMetaData=[]
for match, positions in d.items():
listMetaData.append({"file Name":fileName,"searched Word":match,"number of occurence":len(positions)})
jsondata = json.dumps(listMetaData)
print(jsondata)
【问题讨论】:
-
在我看来,您返回的和预期的结果中缺少几个“,”?
-
json dumps从 dict 返回一个表示 json 对象的字符串。 -
你能分享一下传递给第一个for循环的变量textList的值吗
-
@iam.Carrot 值为
with open(currentFile) as ctf: ctfRead = ctf.read() textList = ctfRead.split('\n')
标签: python json list loops dictionary