拆分python列表

2024-04-24 04:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新手,我写了一个tokenize函数,它基本上接收一个由句子组成的txt文件,并根据空格和标点符号将它们拆分。这里的问题是,它给了我一个在父列表中存在子列表的输出。你知道吗

我的代码:

def tokenize(document)
    file = open("document.txt")
    text = file.read()
    hey = text.lower()
    words = re.split(r'\s\s+', hey)
    print [re.findall(r'\w+', b) for b in words]

我的输出:

[['what', 's', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'eggs', 'warden'], ['his', 'dad', 'was', 'warden', 'in', 'the', 'kitchen', 'poaching', 'eggs']]

期望输出:

['what', 's', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'eggs', 'warden']['his', 'dad', 'was', 'warden', 'in', 'the', 'kitchen', 'poaching', 'eggs']

如何删除输出中的父列表??我需要在代码中做什么更改才能删除外部列表括号??你知道吗


Tags: the代码textinretxt列表document
3条回答

我有一个例子,我想这和你的问题没什么不同。。。你知道吗

我只拿了名单的一部分。你知道吗

>>> a = [['sa', 'bbb', 'ccc'], ['dad', 'des', 'kkk']]
>>> 
>>> print a[0], a[1]
['sa', 'bbb', 'ccc'] ['dad', 'des', 'kkk']
>>> 

这应该管用

print ','.join([re.findall(r'\w+', b) for b in words])

I want them as individual lists

Python中的函数只能返回一个值。如果你想返回两个东西(例如,在你的例子中,有两个单词列表),你必须返回一个可以包含两个东西的对象,比如一个列表,一个元组,一个字典。你知道吗

不要混淆打印输出的方式与返回的对象是什么。你知道吗

只需打印列表:

for b in words:
   print(re.findall(r'\w+', b))

如果您这样做,那么您的方法不会返回任何内容(它实际上返回None)。你知道吗

要返回两个列表:

return [re.findall(r'\w+', b) for b in words]

然后像这样调用您的方法:

word_lists = tokenize(document)
for word_list in word_lists:
    print(word_list)

相关问题 更多 >