Python - Split strings into words within a list of lists

浪子不回头ぞ 提交于 2019-12-25 00:33:34

问题


I have the following list of lists ():

[[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]

and I have the following questions: First, what are these u' appearing in front of every of my sublists? Second, how can I plit my sublists into separate words, i.e. have something like this:

 [[why, not, giving, me, service], [option, to], [removing, an], [verify, name, and], [my, credit, card], [credit, card], [theres, something, on, my, visa]]

I already tried the split function, but I get the following error message: AttributeError: 'list' object has no attribute 'split' Thanx a lot.


回答1:


Code:

list_1 = [[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]
res = []
for list in list_1:
    res.append(str(list[0]).split())

print res

Output:

[['why', 'not', 'giving', 'me', 'service'], ['option', 'to'], ['removing', 'an'], ['verify', 'name', 'and'], ['my', 'credit', 'card'], ['credit', 'card'], ['theres', 'something', 'on', 'my', 'visa']]

u' represents unicode, I hope this answers your question




回答2:


With str.split() function:

l = [[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]

result = [_[0].split() for _ in l]
print(result)

The output:

[['why', 'not', 'giving', 'me', 'service'], ['option', 'to'], ['removing', 'an'], ['verify', 'name', 'and'], ['my', 'credit', 'card'], ['credit', 'card'], ['theres', 'something', 'on', 'my', 'visa']]



回答3:


x=[[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]
[[y.split() for y in m] for m in x]

here's the output of it:

In [3]: [[y.split() for y in m] for m in x]
Out[3]: 
[[[u'why', u'not', u'giving', u'me', u'service']],
 [[u'option', u'to']],
 [[u'removing', u'an']],
 [[u'verify', u'name', u'and']],
 [[u'my', u'credit', u'card']],
 [[u'credit', u'card']],
 [[u'theres', u'something', u'on', u'my', u'visa']]]


来源:https://stackoverflow.com/questions/46928923/python-split-strings-into-words-within-a-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!