gpt4 book ai didi

python - 将逗号分隔的数据转换为不带 CSV 模块的列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:28 25 4
gpt4 key购买 nike

我正在上数据库课,对 python 有点生疏。我的任务如下——

转换此文本:

"col 1", "col 2", "col 3"
1, 'abc', 2
3, "de,fg", 4
5, , 6

进入这个:
[ "col 1", "col 2", "col 3" ]
[ 1, 'abc', 2 ]
[ 3, "de,fg", 4]
[ 5, None, 6]

到目前为止,我所拥有的就是这个(很伤心):
data = open('DatabaseTest.txt', 'r', encoding='utf8').read()
dataS = data.split('\n')

我暂时需要python程序做的就是打印上面的内容。问题是我们不允许使用 CSV 模块,并且 s.split(',')不起作用,因为一个字符串包含逗号。

任何帮助深表感谢。我正在拔头发,因为我找不到任何不包含 CSV 模块的提示。

谢谢!

最佳答案

def smart_split(s,token=","):
in_quotes = False
current_idx = 0
for i,c in enumerate(s):
if c in "\"'":
in_quotes = not in_quotes
elif c == token and not in_quotes:
yield s[current_idx:i].strip()
current_idx = i+1
yield s[current_idx:].strip()

print list(smart_split('3, "de,fg", 4'))
print map(smart_split,open("some_File.txt"))

可能会帮助您入门...可能有更好的方法,但我认为这基本上对您有用...

关于python - 将逗号分隔的数据转换为不带 CSV 模块的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com