从csv arabic文件python中提取一列

时间:2018-06-05 05:22:44

标签: python python-3.x csv arabic

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

# 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()

,文件是这样的:

4   جَوَارِيفُ  جواريف  جرف     اسم 
18  حَرْقى  حرقى    حرق     اسم
24  غَزَواتٌ    غزوات   غزو     اِسْمٌ

我继续给出同样的错误:

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

3 个答案:

答案 0 :(得分:1)

我发现您的代码存在一些问题。首先,您使用open函数的签名与os.open,但它有不同的参数。你可以坚持使用open。更重要的是,您似乎试图通过在标签上再次拆分来修复csv.reader中出现的行。

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

最后,您尝试在将字符串提供给输出文件对象之前对其进行编码。该对象应该使用正确的编码打开,你应该简单地给它字符串。

# 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)

答案 1 :(得分:0)

您可以尝试使用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 注意:我希望它需要阿拉伯语编码。

import pandas as pd 
df = pd.read_csv("filename.csv",encoding='utf-8') 
saved_column = df['اسم'] #change it to str type
# f= open("col.txt","w+",encoding='utf-8') 
with open("col3.txt","w+",encoding='utf-8') as f:
    f.write(saved_column) 

答案 2 :(得分:0)

您可以尝试使用unicodecsv

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()