python - 将类似列表的长字符串转换为新列表
问题描述
我有一个与(预)处理文本信息有关的问题。我在每个 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
解决方案
简单的列表理解
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']
推荐阅读
- javascript - React 导入中的点符号
- ios - pod install 返回错误“网页被阻止”
- python - OpenCV calibrateCamera 中的对象点和图像点
- unix - Cron - 如何在每月特定日期后的第一个工作日运行工作?
- sql - SQL 选择其中一个参数等于另一个表中的另一个参数
- c# - Microsoft Bot 框架技能
- java - 带有 Socket 的 BufferedReader 没有收到任何东西
- c - 初始化包含数组的结构
- regex - 将循环变量传递给 BASH 查找 -regex 参数?
- vb.net - 如何在 Windows 10 上构建自己的 VB.NET 邮件服务器