从csv阿拉伯语文件python中提取列

2024-04-20 13:52:46 发布

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

我试图从一个阿拉伯语文件中提取一个特定的列到另一个文件中 这是我的密码

# coding=utf-8
import csv
from os import open

file = open('jamid.csv', 'r', encoding='utf-8')
test = csv.reader(file)
f = open('col.txt','w+', 'wb' ,encoding='utf-8')
for row in test:

    if len(row[0].split("\t"))>3 :
         f.write((row[0].split("\t"))[3].encode("utf-8"))

f.close()

文件是这样的:

^{pr2}$

我总是犯同样的错误:

File "col.py", line 5, in <module>  file = open('jamid.csv', 'r', encoding='utf-8')
TypeError: an integer is required (got type str)

Tags: 文件csvintestimport密码colopen
3条回答

您可以尝试使用UnicodeSv

How to write UTF-8 in a CSV file

# coding=utf-8
import csv
import unicodecsv as csv

file = open('jamid.csv', 'rb')
test = csv.reader(file, delimiter='\t')
f = open('col.txt', 'wb')
for row in test:
    if len(row)>3 :
         f.write(row[3].encode('utf8'))

f.close()

您可以尝试使用Pandas。我正在发布示例代码。在

import pandas as pd
df = pd.read_csv("Book1.csv")
# print(df.head(10))
my_col = df['اسم'] #Insert the column name you want to select.
print(my_col)

输出: enter image description here 注:我希望它采用阿拉伯语编码。在


^{pr2}$

我看到你的代码有几个问题。首先,使用open函数的签名与os.open,但它有不同的参数。你可以坚持使用open。更重要的是,您似乎试图通过将csv.reader中的行再次拆分到制表符来修复它。在

我的猜测是您看到了row[0]中的整行,所以试图修复它。但问题是读卡器默认情况下以逗号分隔-您需要提供不同的分隔符。这里有点问题,因为代码用制表符拆分,但示例显示空格。我在我的解决方案中使用了空格,但您可以根据需要进行切换。在

最后,尝试在将字符串提供给output file对象之前对字符串进行编码。应该用正确的编码打开该对象,并且只需给它字符串。在

# coding=utf-8
import csv

with open('jamid.csv', 'r', newline='', encoding='utf-8') as in_fp:
    with open('col.txt','w', newline='', encoding='utf-8') as out_fp:
        csv.writer(out_fp).writerows(row[3] for row in
            csv.reader(in_fp, delimiter=' ', skipinitialspace=True)
            if len(row) >= 3)

相关问题 更多 >