Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.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]时删除标点符号_Python - Fatal编程技术网

读取文本文件[python]时删除标点符号

读取文本文件[python]时删除标点符号,python,Python,我正在编写一个python程序,将文本文件的内容读入数组/列表,但在删除文本文件中的标点符号时遇到了问题。以下是我尝试过的: def read_file(self,filename): name_file = filename filename = open(name_file, 'r') file = filename punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct

我正在编写一个python程序,将文本文件的内容读入数组/列表,但在删除文本文件中的标点符号时遇到了问题。以下是我尝试过的:

def read_file(self,filename):
    name_file = filename
    filename = open(name_file, 'r')
    file = filename
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    no_punct = ""
    lst = []
    for word in file:
        word = word.strip('\n')
        for char in punctuations:
            word = word.strip(char)
        lst.append(word)


    filename.close()
def read_文件(self,filename):
name\u file=文件名
filename=open(文件名为'r')
file=文件名
标点符号=“”!()-[]{};:'"\,./?@#$%^&*_~'''
否_punt=“”
lst=[]
对于文件中的word:
word=word.strip('\n')
对于标点符号中的字符:
word=word.strip(字符)
附加(word)
filename.close()
在剥离字符的部分,我注意到word文件中内容的顺序也发生了变化,一些标点符号没有完全删除


如果我使用“replace”方法,它工作得很好,但我正在寻找一种不使用replace内置函数的方法。

我注意到的一些事情只会导致一些标点符号被删除。文件中word:的
行实际上应该是文件中line:
行。Python通过li对文件进行迭代nes,而不是文字。
strip
功能仅从开头和结尾删除项目。您可以使用
replace
功能从中间删除字符。按照当前编写程序的方式,它仅从文档中每行的开头和结尾删除标点符号

我删除所有标点符号的方法是这样的

from pathlib import Path
import string

filepath = Path(filename)
text = filepath.read_text()
text = text.replace(string.punctuation, "")
filepath.write_text(text )

但是你说替换功能与电子书功能有冲突。你能再详细解释一下吗?我看不出在每个单词中替换标点符号与在整个文件中一次替换标点符号有什么不同?

为什么不使用替换功能?添加调用此功能的行很容易?您输入的文本文件的格式是什么?例如,您的文本文件是每行都有一个新词还是全部都是一块文本?@Worm它是以电子书文本文件的形式出现的。换句话说,它有几段文字。@Worm我不鼓励使用“替换”。