【问题标题】:Is there a way to remove punctuation from Persian text?有没有办法从波斯语文本中删除标点符号?
【发布时间】:2022-01-23 12:35:58
【问题描述】:

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

我已经尝试了以下代码:

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' 'چه کسی']

【问题讨论】:

  • 看来你现在拥有的和你想要的之间的区别是波斯字符的一个子集。你能解释一下替换应该做什么吗?

标签: python nlp data-cleaning


【解决方案1】:

您可以使用列表推导来创建一个包含您想要的内容的新列表:

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

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

【讨论】:

  • 另外,'\n'.join(pes_eng).replace("؟!.،,?" ,"").split('\n')
  • 它给出了这个错误:pes_eng[:,1] = [s.replace("؟!.،,?" ,"") for s in pes_eng] AttributeError: 'numpy.ndarray' object has no attribute 'replace'
  • 看来pes_eng 列表中的对象来自ndarray 类型。但是在您的问题中,它们似乎是strings(因为您调用了translate 方法)。您能否显示一些您填写pes_eng 的代码?
  • 我刚刚编辑了帖子,你可以看看,顺便说一下,这个带有德语到英语数据集的工作正常,它正在从两种语言中删除标点符号,但不是波斯语:pes_eng[:,1] = [s.translate(str.maketrans('', '', string.punctuation)) for s in pes_eng[:,1]]
【解决方案2】:

使用这个:

import re
from string import punctuation

cleaned_string = re.sub(f'[{punctuation}؟،٪×÷»«]+', '', string)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2020-05-14
  • 1970-01-01
  • 2013-11-19
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2015-10-21
相关资源
最近更新 更多