gpt4 book ai didi

python - 读取以不同数量的空格作为分隔符的文件?

转载 作者:行者123 更新时间:2023-11-30 23:09:40 31 4
gpt4 key购买 nike

我正在尝试读取一个文件,但它看起来非常尴尬,因为列之间的每个空格都不同。这是我到目前为止所拥有的:

with open('sextractordata1488.csv') as f:
#getting rid of title, aka unusable lines:
for _ in xrange(15):
next(f)
for line in f:
cols = line.split(' ')
#9 because it's 9 spaces before the first column with real data
print cols[10]

我查了一下如何做到这一点,发现 tr 和 sed 命令在我尝试使用它们时给出了语法错误,而且我不太确定将它们放在代码中的哪个位置(在 for 循环中还是之前?)。我想将列之间的所有空格减少到一个空格,以便我能够始终如一地获得一列而不会出现问题(目前,因为它是从 1 到 101 的计数器列,所以我只得到 10 到 99 以及一堆空格和部分之间的其他列,因为 1 和 101 具有不同数量的字符,因此与行开头的空格数量不同)。

最佳答案

只需使用str.split()不带参数。然后将字符串分割为任意宽度的空白。这意味着非空白内容之间有多少空格不再重要:

>>> '   this   is rather     \t\t hard            to parse  without\thelp\n'.split()
['this', 'is', 'rather', 'hard', 'to', 'parse', 'without', 'help']

请注意,前导和尾随空格也会被删除。制表符、空格、换行符和回车符都被视为空白。

为了完整起见,第一个参数也可以设置为 None 以获得相同的效果。这有助于了解何时需要使用第二个参数限制分割:

>>> '   this   is rather     \t\t hard            to parse  without\thelp\n'.split(None)
['this', 'is', 'rather', 'hard', 'to', 'parse', 'without', 'help']
>>> ' this is rather \t\t hard to parse without\thelp\n'.split(None, 3)
['this', 'is', 'rather', 'hard to parse without\thelp\n']

关于python - 读取以不同数量的空格作为分隔符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053721/

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