我正在上一门数据库课,对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模块的提示。
谢谢!
发布于 2015-02-02 14:34:50
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"))也许能帮你入门。可能还有更好的方法,但我认为这对你来说基本上是可行的。
发布于 2015-02-02 15:16:25
这适用于您的特定输入。
data = open('/file', 'r').read()
dataS = [i for i in data.split('\n') if i]
for i in dataS:
print(i.split(', '))输出:
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']通过正则表达式。
import re
data = open('/home/avinash/Desktop/ri', 'r').read()
dataS = [i for i in data.split('\n') if i]
for i in dataS:
print(re.split(r'\s*,\s*(?=(?:"[^"]*"|\'[^\']*\'|[^\'"])*$)', i))输出:
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']发布于 2015-02-02 15:17:35
如果您只想通过使用简单的运算符和条件来解决此问题,请执行以下操作:
data = open("DatabaseTest.txt", 'r').read()
csv = ""
i = 0
l = len(data)
for char in data:
i += 1
if csv == "":
csv += "["
if char == "\n":
csv += "]"
csv += char
csv += "["
else:
csv += char
if char == ",":
if data[i+1] == "," or data[i] == ",":
csv += " None"
if i == l:
csv += "]"
print csv请注意,这不是您的问题的最佳实现,但这肯定会在您的任务中起作用。
还有POOOF!
它只会输出一个字符串,而不是一个列表。
https://stackoverflow.com/questions/28272138
复制相似问题