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

2024-09-29 19:27:53 发布

您现在位置: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 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)

当我运行程序时,什么也没有出现


Tags: 字符串代码in程序forstringopench
3条回答

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

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

使用以下代码检查:

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

这是您代码的修复版本。在

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关键字来打开文件:这样可以确保即使出现错误也能正确关闭文件。例如

^{pr2}$

相关问题 更多 >

    热门问题