从列表中删除标点符号

时间:2017-04-16 04:59:05

标签: string list python-3.x tensorflow punctuation

我正在为语义分析设置一些可用的数据。我有一个原始文本数据语料库,我正在迭代。我打开数据,将其作为字符串读取,拆分为列表,并准备要在以后的函数中构建到数据集中的数据。但是,当我构建数据集时,我最常见的单词最终会被标点符号化。在进一步处理数据之前,我需要从列表中删除所有标点符号。

(Number of new comments: ?)
List of comments:
{% for comment  in task.comments.all %}
     {{ comment.author }}
     {{ comment.created }}
     {{ comment.text }}
{% endfor %}

如果我执行以下操作:

import os
import collections
import string
import sys

import tensorflow as tf
import numpy as np
from six.moves import xrange


totalvocab = []

#Loop for: loop through all files in 'Data' directory
for subdir, dirs, files in os.walk('Data'):
for file in files:
    filepath = subdir + os.sep + file
    print(filepath)

    #Function for: open file, convert input to string, split into list
    def read_data(filepath):
        with open(filepath, 'r') as f:
            data = tf.compat.as_str(f.read()).split()
        return data

    #Run function on data, add file data to full data set.
    filevocab = read_data(filepath)
    totalvocab.extend(filevocab)

    filevocab_size = len(filevocab)
    print('File vocabulary size: %s' % filevocab_size)
    totalvocab_size = len(totalvocab)
    print('Total vocabulary size: %s' % totalvocab_size)

这些单词被分成单独的字母。 我试过的任何其他方法都有错误。

1 个答案:

答案 0 :(得分:1)

代码中有一些错误:

  1. str.split()str.translate()不会进行适当修改。
  2. str.translate()需要映射。
  3. 修复:

    def read_data(filepath):
        with open(filepath, 'r') as f:
            data = tf.compat.as_str(f.read())
        data = data.translate(str.maketrans('', '', string.punctuation))
        return data.split()
    

    删除标点符号,可能会也可能不会执行您想要的操作,例如:带连字符的单词将被连接起来。您也可以识别要用空格替换的标点符号。