有没有办法从波斯文字中删除标点符号?

时间:2019-05-12 14:38:17

标签: python nlp data-cleaning

我想摆脱文本文件中的标点符号,这是一个英语-波斯语句子对数据。

我尝试了以下代码:

import string
import re
from numpy import array, argmax, random, take
import pandas as pd

# function to read raw text file
def read_text(filename):
    # open the file
    file = open(filename, mode='rt', encoding='utf-8')

    # read all text
    text = file.read()
    file.close()
    return text

# split a text into sentences
def to_lines(text):
  sents = text.strip().split('\n')
  sents = [i.split('\t') for i in sents]
  return sents


data = read_text("pes.txt")
pes_eng = to_lines(data)
pes_eng = array(pes_eng)

# Remove punctuation
pes_eng[:,0] = [s.translate(str.maketrans('', '', string.punctuation)) for s         
in pes_eng[:,0]]
pes_eng[:,1] = [s.replace("؟!.،,?" ,"") for s in pes_eng]

print(pes_eng)

上面的代码适用于英语句子,但对波斯语句子则无济于事。

这里的输出是:

Traceback (most recent call last):
  File ".\persian_to_english.py", line 29, in <module>
    pes_eng[:,1] = [s.replace("؟!.،,?" ,"") for s in pes_eng]
  File ".\persian_to_english.py", line 29, in <listcomp>
    pes_eng[:,1] = [s.replace("؟!.،,?" ,"") for s in pes_eng]
AttributeError: 'numpy.ndarray' object has no attribute 'replace'

但是我想要的是这样的:

['Who' 'چه کسی']

1 个答案:

答案 0 :(得分:1)

您可以使用列表推导来创建包含所需内容的新列表:

new_pes_eng = [s.replace("؟!.،,?" ,"") for s in pes_eng]

上面的行从您的replace()列表项中删除了标点符号(传递给pes_eng的第一个参数中的标点符号)。