【问题标题】:How do I keep only ascii and discard non-ascii, nbsp, etc while doing json.dumps如何在做 json.dumps 时只保留 ascii 并丢弃非 ascii、nbsp 等
【发布时间】:2020-05-15 20:00:17
【问题描述】:

我使用 csv reader 读取 csv 文件,然后使用字典将其转换为 json 文件。
这样做时,我只想要没有非 ascii 字符或 nbsp 的字母和数字。我正在尝试这样做:

with open ('/file', 'rb') as file_Read:
     reader = csv.reader(file_Read)
     lis = []
     di = {}
     for r in reader:
         di = {r[0].strip():[some_val]}
         lis.append(di)

with open('/file1', 'wb') as file_Dumped:
     list_to_be_written = json.dumps(lis)
     file_Dumped.write(liss)

当我读取文件时,输出包含像\xa0\xa0\xa0\xa0 这样的序列以及键。
前 - {"name \xa0\xa0\xa0\xa0":[9]}
如果我执行json.dumps(lis,ensure_ascii=False),那么我会看到按键周围有空格。
前 - {"name ":[9]}
如何完全删除除字母和数字之外的所有内容?

【问题讨论】:

  • import string printable = set(string.printable) ''.join(filter(lambda x: x in printable, list_to_be_written))
  • @HarishKumar 非常有帮助,先生。我添加了 strip(),它给了我想要的结果。

标签: python ascii non-ascii-characters python-unicode


【解决方案1】:

你可以试试这个:

import pandas as pd
import json
# Read the csv file using pandas
df = pd.read_csv("YourInputCSVFile")

#Convert all column types to str in order to remove non-ascii characters
df = df.astype(str)

#Iterate between all columns in order to remove non-ascii characters
for column in df:
    df[column] = df[column].apply(lambda x: ''.join([" " if ord(i) < 32 or ord(i) > 126 else i for i in x]))

#Convert the dataframe to dictionary for json conversion
df_dict = df.to_dict()

#Save the dictionary contents to a json file
with open('data.json', 'w') as fp:
    json.dump(df_dict, fp)

【讨论】:

    【解决方案2】:

    如果空格只在行尾,您可以使用.strip()。如果你需要在 ascii 字符之间留空格,你可以使用这样的:

    my_string.replace('  ', '').strip()
    

    要删除非ASCII字符,试试这个:

    my_string = 'name  \xa0\xa0\xa0\xa0'
    my_string.encode('ascii', 'ignore').strip()
    

    【讨论】:

    • 感谢您的回复,先生。我已经在那里删除了尾随/前导空格(for循环中的第一行)。考虑一下 - s = '\xef\xbb\xbf name1'。如果您键入 print s,在 Python 空闲时,输出将是 name1。如果您键入 s 输出将是 '\xef\xbb\xbf name1'。如何删除 '\xef\xbb\xbf '
    • 试试这样的:my_string = 'name \xa0\xa0\xa0\xa0'my_string.encode('ascii', 'ignore').strip()
    • 它给出了这个错误 - UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 5: ordinal not in range(128)
    • 请在此处查看类似问题的解决方案 (stackoverflow.com/questions/46154561/…)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2014-05-29
    相关资源
    最近更新 更多