假设我有以下多行字符串。我们可以假设title后面总是跟一行。
"""
This is title
-------------------------
Author: Name of the author
Sentence 1.
Sentence 2.
"""
我想把它转换成这样的字典:
{
"title": "This is title",
"author": "Name of the author",
"body": "sentence 1.nnSentence 2.",
}
如何将前两行与所有这些"-----"然后把剩下的行分成一行?你能给我一些建议吗?
假设这是所有给定字符串的标准布局。您可以使用多重赋值和str.split
来将您的值拆分为变量,然后构建dict
。你只需要使用str.join
来重新连接被分开后的字符串:
s = """
This is title
-------------------------
Author: Name of the author
Sentence 1.
Sentence 2.
"""
_, title, _, author, *body = s.split('n')
data = {
"title": title,
"author": ' '.join(author.split()[1:]),
"body": 'n'.join(body)
}
PrettyPrinted输出:
{'title': 'This is title',
'author': 'Name of the author',
'body': 'nSentence 1.nnSentence 2.n'}
虽然这可以工作,但对于现实世界的应用程序来说有点混乱/特别。如果你想要一个更具体的解决方案,请看看是否可以重新格式化数据的提供/存储方式。
我是这样解决这个问题的:
哪个部分可以被认为是一致的?
依我看,标题、标题行和作者是一致的。Regex允许我们描述我们期望的字符串格式,因此,我编写了一个Regex格式来描述一致的部分。
我怎么得到剩下的?
Regex还允许我们存储匹配的start
和end
位置。我们可以用这些点来建立"其余的"。
为什么不直接将正文添加到格式中呢?
我无法用简单的方法把它弄明白。对于双行和单行新行,有太多的条件可以重叠下一个条目(如果有的话)。import re
#describe the format of an entry
fmt = re.compile(r'^(?P<title>([wd ]+))n([-]+)nAuthor: (?P<author>([wd ]+))nn', re.I|re.M)
# SINGLE ENTRY
dat = ('Title 1n'
'-------------------------n'
'Author: Some Guynn'
'Sentence 1.nn'
'Sentence 2.nn')
#get entry
m = fmt.search(dat)
#make entry
book = dict(title=m.group('title'), author=m.group("author"), body=dat[m.end():len(dat)]) if m else None
#print book
print(book)
# MULTIPLE ENTRIES
dat = ('Title 1n'
'-------------------------n'
'Author: Some Guynn'
'Sentence 1.nn'
'Sentence 2.nn'
'Title 2n'
'-------------------------n'
'Author: Some Other Guynn'
'Sentence 1.nSentence 2nn'
'Sentence 3.nn')
#prime books
books = list()
#for storing data that needs to be carried over to the next iteration
le, lt, la = -1, "", ""
#make all but last entry
for m in fmt.finditer(dat):
#this is always behind by 1 because we have to get `le` once before we can do this
if le > -1: books.append(dict(title=lt, author=la, body=dat[le:m.start()]))
#store this data to be carried over to the next iteration
le, lt, la = m.end(), m.group('title'), m.group("author")
#make last entry
books.append(dict(title=lt, author=la, body=dat[le:len(dat)]))
#print all books
print(books)