String 从列表中删除标点符号

String 从列表中删除标点符号,string,list,python-3.x,tensorflow,punctuation,String,List,Python 3.x,Tensorflow,Punctuation,我正在为语义分析设置一些可用的数据。我有一个我正在迭代的原始文本数据的语料库。我打开数据,将其作为字符串读取,拆分成一个列表,并准备在以后的函数中将数据构建到数据集中。然而,当我构建数据集时,我最常用的单词是标点符号。在进一步处理数据之前,我需要删除列表中的所有标点符号 import os import collections import string import sys import tensorflow as tf import numpy as np from six.moves i

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

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)
如果我这样做:

def read_data(filepath):
        with open(filepath, 'r') as f:
            data = tf.compat.as_str(f.read())
            data.translate(string.punctuation)
            data.split()
        return data
这些单词被分成几个字母。
我尝试的任何其他方法都已出错。

代码中有几个错误:

  • str.split()
  • str.translate()
    需要一个映射
  • 要修复:

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

    删除标点符号,可以执行也可以不执行您想要的操作,例如,连字符的单词将连接在一起。您也可以用空格替换标点符号。

    非常感谢!这正是我所需要的。你预测我未来的需求也是正确的,因为连字符的单词需要包含在我的数据中。我将如何声明要替换的标点符号?