将行拆分为类别和文本

Shi*_*ifu 0 python split

我的列表看起来像这样:

foo = ["neg * , This is a sentence","pos * , This is another sentence"]
Run Code Online (Sandbox Code Playgroud)

我需要将句子分成一个值,即一个值将成为类别,neg或者pos一个句子.我试过了:

for text in foo:
    text = text.split("*")
    for a,b in text:
        cat=a
        text=b
Run Code Online (Sandbox Code Playgroud)

但是我得到了"太多的价值来打开包装",任何人都有一个想法?

Inb*_*ose 6

你的问题是你的循环是非常可靠的(这是可以原谅的,因为你显然是对整个事物的新手)

尝试这种更安全的方法(列表理解):

>>> foo = ["neg * , This is a sentence","pos * , This is another sentence"]
>>> [p.split('*', 1) for p in foo]
[['neg ', ' , This is a sentence'], ['pos ', ' , This is another sentence']]
Run Code Online (Sandbox Code Playgroud)

现在你有一个[CAT, TEXT]项目列表.

>>> l = [p.split('*', 1) for p in foo]
>>> for cat, text in l:
    print 'cat: %s, text: %s' % (cat, text)

cat: neg , text:  , This is a sentence
cat: pos , text:  , This is another sentence
Run Code Online (Sandbox Code Playgroud)