Skip to main content
 首页 » 编程设计

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

2024年10月25日11虾米哥

我正在上数据库课,对 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")) 

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