簡體   English   中英

在Python中讀取具有多個空格作為分隔符的txt文件

[英]Reading txt file with more than one space as a delimiter in Python

我有一個文本文件,其中的列由多個空格分隔 問題是每列中的值也可以分隔,但最多只有一個空格 所以它可能看起來像這樣

aaaxx   123 A   xyz   456 BB 
zcbb  a b   XYZ   xtz 1 
cdddtr  a  111  tddw

有沒有辦法閱讀這樣的表格? 我嘗試了一些方法,我認為我必須使用某種正則表達式作為分隔符,但老實說,我不知道如何解決這個問題。

您可能想使用正則表達式

import re

content = """aaaxx   123 A   xyz   456 BB 
zcbb  a b   XYZ   xtz 1 
cdddtr  a  111  tddw
"""

# Split the content on new lines
rows = content.split("\n")

# Create a 2D list (table) out of the values
table = []

for row in rows:
    row_arr = []
    # The "[ ]" is the regexp equivalent of "space" and {2,} means 2+
    for column in re.split("[ ]{2,}", row):
    # If the row is empty, don't add it to the table
    if len(row_arr):
        table.append(row_arr)

print(table)

其他解決方案,使用pandas

import pandas as pd

df = pd.read_csv("your_file.txt", sep=r"\s{2,}", engine="python", header=None)
print(df)

印刷:

        0      1    2       3
0   aaaxx  123 A  xyz  456 BB
1    zcbb    a b  XYZ   xtz 1
2  cdddtr      a  111    tddw

這是我將使用的兩個實現。 它們基於奇偶校驗:用兩個空格分隔的值保持由一個空格分隔的值在一起,由偶數個空格分隔的值被正確拆分,不均勻的情況用strip方法清除。 剩余的空字符串被過濾掉。

content = """aaaxx   123 A   xyz   456 BB 
zcbb  a b   XYZ   xtz 1 
cdddtr  a  111  tddw"""


def split_file_content(file_content: str) -> list[list[str]]:
    """If you don't like regex"""
    return [
        [part.strip() for part in row.split("  ") if part]
        for row in file_content.split("\n")
    ]


def split_file_content_loops(file_content: str) -> list[list[str]]:
    """If you don't like regex AND list comprehensions"""
    table = []
    for row in file_content.split("\n"):
        values = []
        for part in row.split("  "):
            if part:
                values.append(part.strip())
        table.append(values)
    return table


print(split_file_content(content))
print(split_file_content_loops(content))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM