我正在尝试从嵌套和标记化列表中删除标点符号。我已经尝试了几种不同的方法来解决这个问题,但没有成功。我最近的尝试是这样的:
def tokenizeNestedList(listToTokenize):
flat_list = [item.lower() for sublist in paragraphs_no_guten for item in sublist]
tokenList = []
for sentence in flat_list:
sentence.translate(str.maketrans(",",string.punctuation))
tokenList.append(nltk.word_tokenize(sentence))
return tokenList
正如您所看到的,当我标记列表时,我正在尝试删除标点符号,在调用我的函数时,遍历了该列表。但是,当尝试这种方法时,我得到了错误
ValueError: the first two maketrans arguments must have equal length
我有点理解为什么会发生。运行我的代码而没有尝试删除标点符号并打印前10个元素,这使我(因此您对我的工作有所了解):
[[], ['title', ':', 'an', 'inquiry', 'into', 'the', 'nature', 'and', 'causes', 'of', 'the', 'wealth', 'of', 'nations'], ['author', ':', 'adam', 'smith'], ['posting', 'date', ':', 'february', '28', ',', '2009', '[', 'ebook', '#', '3300', ']'], ['release', 'date', ':', 'april', ',', '2002'], ['[', 'last', 'updated', ':', 'june', '5', ',', '2011', ']'], ['language', ':', 'english'], [], [], ['produced', 'by', 'colin', 'muir']]
任何人和所有建议都值得赞赏。
答案 0 :(得分:2)
假设每个标点符号都是一个单独的标记,则可以这样:
import string
sentences = [[], ['title', ':', 'an', 'inquiry', 'into', 'the', 'nature', 'and', 'causes', 'of', 'the', 'wealth', 'of',
'nations'], ['author', ':', 'adam', 'smith'],
['posting', 'date', ':', 'february', '28', ',', '2009', '[', 'ebook', '#', '3300', ']'],
['release', 'date', ':', 'april', ',', '2002'], ['[', 'last', 'updated', ':', 'june', '5', ',', '2011', ']'],
['language', ':', 'english'], [], [], ['produced', 'by', 'colin', 'muir']]
result = [list(filter(lambda x: x not in string.punctuation, sentence)) for sentence in sentences]
print(result)
输出
[[], ['title', 'an', 'inquiry', 'into', 'the', 'nature', 'and', 'causes', 'of', 'the', 'wealth', 'of', 'nations'], ['author', 'adam', 'smith'], ['posting', 'date', 'february', '28', '2009', 'ebook', '3300'], ['release', 'date', 'april', '2002'], ['last', 'updated', 'june', '5', '2011'], ['language', 'english'], [], [], ['produced', 'by', 'colin', 'muir']]
这个想法是使用filter来删除那些标点符号,因为filter返回一个迭代器使用列表,将其转换回列表。您还可以使用等效的列表理解:
result = [[token for token in sentence if token not in string.punctuation] for sentence in sentences]
答案 1 :(得分:1)
要使其正常工作,您需要运行Python3.x。 另外,b包含您提供的示例嵌套列表
import string
# Remove empty lists
b = [x for x in b if x]
# Make flat list
b = [x for sbl in b for x in sbl]
# Define translation
translator = str.maketrans('', '', string.punctuation)
# Apply translation
b = [x.translate(translator) for x in b]
# Remove empty strings
b = list(filter(None, b))
为什么以前不起作用的参考: Python 2 maketrans() function doesn't work with Unicode: "the arguments are different lengths" when they actually are