简体   繁体   English

Python-将字符串分成列表列表中的单词

[英]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? 我有以下问题:首先,这些u'出现在每个子列表的前面吗? 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. 我已经尝试了split函数,但是收到以下错误消息: AttributeError: 'list' object has no attribute 'split'

With str.split() function: 使用str.split()函数:

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 代表unicode,我希望这能回答你的问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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