如何在Python中删除字符串中的标点符号?

如何在Python中删除字符串中的标点符号?,python,Python,我试图删除字符串中的所有标点符号,但每当我运行我的程序时,什么都不会发生。。。这是我的代码: #OPEN file (a christmas carol) inputFile = open('H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt') carolText = inputFile.read() #CONVERT everything into lowercase for l

我试图删除字符串中的所有标点符号,但每当我运行我的程序时,什么都不会发生。。。这是我的代码:

#OPEN file (a christmas carol)
inputFile = open('H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt')
carolText = inputFile.read()



#CONVERT everything into lowercase
for line in carolText:
       carolTextlower = carolText.lower()

#REMOVE punctuation (Put a space instead of a hyphened word or apostrophe)
import string
exclude = set(string.punctuation)
noPunctu = carolTextlower.join(ch for ch in carolTextlower if ch not in exclude)
print(noPunctu)

当我运行程序时,不会显示任何内容,请检查以下代码:

import string

inputFile = open('H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt')
carolText = inputFile.read()

for c in string.punctuation:
    carolText=carolText.replace(c,"")

carolText

以下是如何打开文件,替换其中的某个字符,然后将所有内容重新写入新文件

to_replace = '-'  # Hyphen
replace_by = ' '  # Space

# Reading the file to be modified.
with open('file.txt', 'r') as file:
    # Modifying the contents as the file is being read.
    new_file = [line.replace(to_replace, replace_by) for line in file]

# Writing the contents, both modified and untouched ones, in a new file. 
with open('file_modified.txt', 'w') as file:
    for item in new_file:
        print(item, file=file, end='\n')

这可以使用Python的translate函数来完成。代码生成一个表,将任何大写字符映射为匹配的小写字符,并将任何标点字符转换为空格。这是在对整个文本的一次调用中完成的,因此速度非常快:

import string

def process_text(s):
    return s.translate(
        str.maketrans(
            string.punctuation + string.ascii_uppercase, 
            " " * len(string.punctuation) + string.ascii_lowercase)).replace("  ", " ")

with open(r'H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt') as inputFile:
    print(process_text(inputFile.read()))

这是您的代码的修复版本

import string

#OPEN file (a christmas carol)
inputFile = open(r'H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt')
carolText = inputFile.read()
inputFile.close()

#CONVERT everything into lowercase
carolTextlower = carolText.lower()

#REMOVE punctuation 
exclude = set(string.punctuation)
noPunctu = ''.join(ch for ch in carolTextlower if ch not in exclude)
print(noPunctu)
通常的Python约定是将import语句放在脚本的顶部,这样就很容易找到它们

注意,我在文件名的开头引号之前使用了一个由r表示的原始字符串。这里并不严格需要,但它可以防止Windows路径中的反斜杠序列被解释为转义序列。例如,在“H:\Documents\new\test.py”中,\n将被解释为换行符,\t将被解释为制表符

您真的应该在完成文件的读写之后关闭它。但是,最好使用with关键字打开文件:这样可以确保即使出现错误,文件也能正确关闭。例如

filename = r'H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt'
with open(filename) as inputFile:
    carolText = inputFile.read()

有人能提供更多的细节吗。你是如何运行这个程序的?您使用的是什么版本的Python?什么是inputFile?我试过了,但有人把它删除了--这是构建代码所需的全部内容。这甚至不可读,阿尔贝托!好吧,你做得更好