Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将文本文件转换为字符串(Python 3)_Python_Text_Python 2.x - Fatal编程技术网

将文本文件转换为字符串(Python 3)

将文本文件转换为字符串(Python 3),python,text,python-2.x,Python,Text,Python 2.x,我想将一个文本文件转换成一个字符串,我从这个函数开始,它是用Python 2编写的: def parseOutText(f): f.seek(0) all_text = f.read() content = all_text.split("X-FileName:") words = "" if len(content) > 1: text_string = content[1].translate(string.maketran

我想将一个文本文件转换成一个字符串,我从这个函数开始,它是用Python 2编写的:

def parseOutText(f):
    f.seek(0)  
    all_text = f.read()

    content = all_text.split("X-FileName:")
    words = ""
    if len(content) > 1:
        text_string = content[1].translate(string.maketrans("", ""), string.punctuation)

        words = text_string

        ### split the text string into individual words, stem each word,
        ### and append the stemmed word to words (make sure there's a single
        ### space between each stemmed word)

    return words

正如您所看到的,我必须向这个函数添加一些代码,但它没有编译(编译器给出错误,说“string”没有函数“maketrans”)。我确信这段代码可以很容易地翻译成Python3,但直到注释行出现,我才真正理解它的功能。它只是省略了标点符号并将文本转换为字符串吗?

因此我找到了这段代码,它就像一个符咒:

exclude = set(string.punctuation)
string = ''.join(ch for ch in string if ch not in exclude)
Python3.x和具有其Python2前身的所有基本功能,以及更多功能,但它们有不同的API。所以,你必须了解他们在做什么来使用它们

在2.x中,使用了一个非常简单的
,make by,以及一个单独的
deletechars
列表

在3.x中,表更加复杂(很大程度上是因为它现在转换的是Unicode字符,而不是字节,但它还有其他新功能)。该表由静态方法
str.maketrans
而不是函数
string.maketrans
生成。并且该表包含删除列表,因此不需要单独的参数来
translate

从文档中:

static str.maketrans(x[, y[, z]])
此静态方法返回可用于
str.translate()
的转换表

如果只有一个参数,则必须是将Unicode序号(整数)或字符(长度为1的字符串)映射到Unicode序号、字符串(任意长度)或
None
的字典。然后,字符键将转换为序数

如果有两个参数,它们必须是长度相等的字符串,并且在生成的字典中,x中的每个字符都将映射到y中相同位置的字符。如果有第三个参数,则必须是字符串,其字符将映射到结果中的
None


因此,要创建一个表,删除所有标点符号,在3.x中不做任何其他操作,请执行以下操作:

table = str.maketrans('', '', string.punctuation)
并将其应用于:

translated = s.translate(table)

同时,由于您使用的是Unicode,您确定
string.标点符号是您想要的吗?正如我们所说,这是:

在C语言环境中被视为标点字符的ASCII字符字符串

因此,例如,卷曲引号、英语以外语言中使用的标点符号等不会被删除

如果这是一个问题,你必须这样做:

translated = ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'P')

换行

text_string = content[1].translate(string.maketrans("", ""), string.punctuation)'
对此

text_string = content[1].translate((str.maketrans("", ""), string.punctuation)) '

我确信它的
str.maketrans()
@Emmanuel似乎是正确的,现在它告诉我函数只接受一个参数是错误的。我只是删除了第二个参数,它会打印文本,但不会删除punctuation@Ach113那不可能是对的。可选地接受三个参数,而不仅仅是一个。无论如何,请阅读
maketrans
translate
的文档。它们与Python2.x函数不完全相同,因此如果您想使用它们,必须了解它们在做什么。