清理python中的文本

2024-10-02 20:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始用python编写代码,我有一个数据集,其中两个列给了我一些问题。其中一个有艺术家的原籍国信息,还有一些有双重国籍,比如:法国/美国。我只想得到第一个国家,在这里是法国。在第二栏,我有艺术家的名字,但其中一些有奇怪的字符,例如:GyÌrgy Kepes。清洁这些元件的最佳方法是什么?如果这有帮助,我将按以下方式打开文件:

 data = pd.read_csv(fpn_csv, encoding='ISO-8859-1')

我不知道这是否以任何方式影响了我的进程,但是如果我使用UTF-8,我无法打开文件

列的名称为:

原产国和艺术家。你知道吗

以下是我的文件示例:

+------+-------------------------------+-----------------------------+-------------------+-------------------------+------------+-----------------+
| ID   |         artist_title          |        art_movement         |   museum_venue    |    country_of_origin    |  has_text  |  primary_medium |
+------+-------------------------------+-----------------------------+-------------------+-------------------------+------------+-----------------+
| 361  |  LÌÁszlÌ_ Moholy-Nagy         |  Vertical Black, Red, Blue  |  LACMA also MoMA  |  Hungary                |  FALSE     |  sculpture      |
| 362  |  BrassaÌø (Gyula HalÌÁsz)     |  Buttress of the Elevated   |  MoMA             |  Transylvania / France  |  FALSE     |  photography    |
| 363  |  M. C. Escher                 |  Relativity                 |  MoMA             |  Denmark                |  FALSE     |  print          |
| 364  |  Clyfford Still 1944-N No. 2  |  abstract expressionism     |  MoMA             |  America                |  FALSE     |  painting       |
| 365  |  Harold E. Edgerton           |  Milk Drop                  |  MoMA             |  America                |  FALSE     |  photography    |
| 366  |  Meret Oppenheim Object       |  surrealism                 |  MoMA             |  Germany / Switzerland  |  FALSE     |  sculpture      |
+------+-------------------------------+-----------------------------+-------------------+-------------------------+------------+-----------------+

Tags: 文件ofcsv数据代码信息false方式
1条回答
网友
1楼 · 发布于 2024-10-02 20:38:03

如果您想删除坏字符,您可以简单地编码为ascii。你知道吗

>>> s = 'Gy̦rgy Kepes'
>>> s.encode('ascii', errors='ignore').decode()
Gyrgy Kepes

如果您不介意输出类型为bytes,则不需要解码

另一种方法可能是使用filter

>>> import string
>>> good = set(string.printable) # 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 
>>> s = 'Gy̦rgy Kepes'
>>> ''.join(filter(lambda x: x in good, s))
Gyrgy Kepes

相关问题 更多 >