2016-02-08 1838 views
-3

我想從字符串中刪除所有的標點,但每當我跑我的程序沒有任何反應......這是我的代碼:如何從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) 

當我運行我的程序,沒有出現

+0

有人可以請幫忙 –

+1

提供更多的細節。你如何運行該程序?你使用的是什麼版本的Python?什麼是'inputFile'? –

+0

我試過了,但有人把它全部刪除了 –

回答

0

這是修復的代碼版本。

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

檢查與以下代碼:

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 
0

以下是如何打開文件,替換其中的某個字符,然後再將所有內容寫入新文件。

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

這可以使用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())) 
相關問題