首页 > 解决方案 > 将类似列表的长字符串转换为新列表

问题描述

我有一个与(预)处理文本信息有关的问题。我在每个 csv 行中的数据结构如下:

row = "['Adventure' 'African elephant' 'Animal' 'Ball game' 'Bay' 'Body of water' 'Communication Device' 'Electronic device']"

转换后的期望结果:

[adventure, african_elephant, animal, ball_game, bay, body_of_water, communication_device, electronic_device]

问题: 我怎样才能最好和最有效地解决这个问题(100,000 个文档)?欢迎使用 Python 中的 RegEx 和非 RegEx 解决方案。

解决方案:

%%time
import ast
row = "['Adventure' 'African elephant' 'Animal' 'Ball game' 'Bay' 'Body of water' 'Communication Device' 'Electronic device']"
row = ast.literal_eval(','.join(['_'.join(i.lower().split()) for i in row.split("' '")]))[0].split(',')
row

CPU times: user 43 µs, sys: 1 µs, total: 44 µs
Wall time: 48.2 µs

%%time
row = "['Adventure' 'African elephant' 'Animal' 'Ball game' 'Bay' 'Body of water' 'Communication Device' 'Electronic device']"
row = [w.lower().replace(' ', '_') for w in re.findall(r"'([^']*)'", row)]
row

CPU times: user 25 µs, sys: 1e+03 ns, total: 26 µs
Wall time: 29.1 µs

标签: pythonregexscikit-learn

解决方案


简单的列表理解

import ast
document = "['Adventure' 'African elephant' 'Animal' 'Ball game' 'Bay' 'Body of water' 'Communication Device' 'Electronic device']"
ast.literal_eval(','.join(['_'.join(i.lower().split()) for i in document.split("' '")]))

输出(作为包含单个字符串的列表)

['adventure,african_elephant,animal,ball_game,bay,body_of_water,communication_device,electronic_device']

现在,如果您需要字符串列表

ast.literal_eval(','.join(['_'.join(i.lower().split()) for i in document.split("' '")]))[0].split(',')

输出

['adventure',
 'african_elephant',
 'animal',
 'ball_game',
 'bay',
 'body_of_water',
 'communication_device',
 'electronic_device']

推荐阅读