【问题标题】:Function to read csv string读取csv字符串的函数
【发布时间】:2021-10-23 02:13:18
【问题描述】:

此问题与现在已删除的 earlier question 重复,现在已根据原始中提供的 cmets 进行编辑。

我正在尝试创建一个以 CSV 格式输入字符串的函数。例如"id,name,age,score\n1,Jack,NULL,12\n17,Betty,28,11"

它应该返回下表:

id name age score
1 Jack NULL 12
17 Betty 28 11

它还应该删除有缺陷的行。有缺陷的行是当它的值 NULL 全部大写时 - 任何其他字符,如(0 到 9 或 a 到 z 或 A 到 Z)都是可以接受的。

上述输入字符串的最终输出应该是:

id name age score
17 Betty 28 11

这是我使用 pandascsv 包的代码。我需要在不使用任何这些包的情况下创建它。

def test(S):
    result = pd.DataFrame(csv.reader(S.splitlines()))
    new_header = result.iloc[0]
    result = result[1:]
    result.columns = new_header 
    df = result.select_dtypes(object)
    new_result = ~df.apply(lambda series: series.str.contains('NULL')).any(axis=1)
    f_result = result[new_result]
    return f_result

【问题讨论】:

  • 请不要转发问题!等待编辑后重新打开。
  • 我很难相信有人会因为你不能或不想使用它们而花时间为你重新实现这些库。您必须亲自尝试,并就您在此过程中将面临的具体问题提出具体问题
  • 请先试一试,再提问。你想用python写吗?
  • "上述输入字符串的最终输出应该是" 渲染的降价表对于 Python 来说不是一个明智的输出,尤其是在没有包的情况下。期望的输出到底是什么?如果连内置的 csv 模块都被禁止了,你还能使用哪些功能?您刚刚手动拆分输入有什么问题?您必须支持哪些 csv 功能,例如引号还是多行值?
  • @martineau,感谢您重新提出问题。

标签: python csv


【解决方案1】:

这里是如何做你说你想做的事。您对所需“表格”输出的描述有些模糊,所以我做出了最好的猜测。

def get_rows(data):
    rows = []
    for line in data.splitlines():
        fields = line.split(',')
        if not any(field == 'NULL' for field in fields):  # Not defective row.
            rows.append(fields)
    return rows


csv_string = 'id,name,age,score\n1,Jack,NULL,12\n17,Betty,28,11'
rows = get_rows(csv_string)

# Find longest item in each column.
widths = [max(len(item) for item in col) for col in zip(*rows)]

# Create a row of separators and make it the second row of the list.
separator_row = [width*'-' for width in widths]
rows.insert(1, separator_row)  # Insert following header row.

# Create a format specification for rows of table.
field_specs = [f' {{:{width}}} ' for width in widths]
format_spec = '|' + '|'.join(field_specs) + '|'

# Print formatted data.
for row in rows:
    print(format_spec.format(*row))

纯文本示例输出:

| id | name  | age | score |
| -- | ----- | --- | ----- |
| 17 | Betty | 28  | 11    |

【讨论】:

  • 输出格式正是我想要的。我尝试过这样def test(s): o = [] for line in s.splitlines(): if "NULL" in line: continue words = line.split(",") o.append(words) return o,但无法获得所需的格式。
  • 这还不错,但是if "NULL" in line: 的一个潜在问题是它会拒绝1,Jack,notNULL,12,尽管从技术上讲它不应该——尽管可能不太可能有任何这样的真实数据。
猜你喜欢
  • 1970-01-01
  • 2016-01-27
  • 2011-06-22
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多