简体   繁体   中英

Python - Split strings into words within a list of lists

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, ie 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.

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']]

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

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']]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM