假设我有一个带有一些注释的文本文件,然后键和值如下:
# The following is
# a list of words and their positions
I: 1
like: 2
to: 3, 5
go: 4
cafes: 6
我怎么会把这变成一句话('我喜欢去咖啡馆')?我想我应该首先尝试将文本转换为字典,但是在删除注释并将其拆分为键和值时已经有问题了...... 任何帮助都会很棒!
答案 0 :(得分:4)
读取文件,将单词和位置作为元组附加到列表中。然后对该列表进行排序,删除索引并加入单词:
with open(inputfilename) as inputfile:
words = []
for line in inputfile:
line = line.strip()
if not line or line.startswith('#'):
continue
word, positions = line.split(':')
words.extend((int(p), word) for p in positions.split(','))
print ' '.join([w for p, w in sorted(words)])
演示:
>>> with open(inputfilename) as inputfile:
... words = []
... for line in inputfile:
... line = line.strip()
... if not line or line.startswith('#'):
... continue
... word, positions = line.split(':')
... words.extend((int(p), word) for p in positions.split(','))
...
>>> print ' '.join([w for p, w in sorted(words)])
I like to go to cafes
答案 1 :(得分:0)
步骤1将内容读入dict
第2步,排序以对dict中的内容进行排序。
shep3然后最终使用foreach获取值,然后用+连接以生成句子。