开发者

read text file (colon-separated words) and get a list of tuples

I have a text file called words.txt of word & description pairs separated by a colon, example:

word1:description 1 bla bla bla
word2:descrip开发者_Python百科tion 2 blah blah
...

I want a structure like this one:

[('word1', 'description 1 bla'), ('word2', 'description 2 blah')]

if you think another structure different than a list of tuples is better just tell me...I would love the solution by using list comprenhesion but I'm stucked.


How about just:

[line.split(':', 1) for line in open('words.txt')]

or

dict(line.split(':', 1) for line in open('words.txt'))


data = []
for line in open('file.txt'):
  data.append(tuple(line.strip().split(':')))

The 'tuple' is only there to change the list returned by split to a tuple.

Optionally do:

data = dict(data)

afterward to change it into a word:description dictionary, which may be a better representation of what you want.


Or you can do the following

text = """
          word1:description 1 bla bla bla
          word2:description 2 blah blah
       """
[tuple(x.strip().split(':', 1)) for x in text.split('\n') if ':' in x]


[tuple(line.partition(':')[0:3:2]) for line in open('file.txt')]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜