[英]Python function to replace letters
我需要刪除標點符號,我將問題放在下面,並將代碼放在下面。 我不確定什么不起作用以及我缺少什么 - 我試圖讓它盡可能基本/簡單,並且只使用我迄今為止學到的初學者的東西。 它說要使用 replace() 所以這就是我試圖做的。 謝謝!
定義一個名為 strip_punctuation 的 function,它采用一個參數,一個表示單詞的字符串,並從單詞中的任何位置刪除被認為是標點符號的字符。 (提示:記住字符串的 .replace() 方法。)
def strip_punctuation(punctuations):
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
for item in punctuations:
if item in punctuation_chars:
punctuations.replace(item, "")
return punctuations
Python 字符串是不可變的。 str.replace
不修改字符串,它返回一個新字符串。 所以你要
punctuations = punctuations.replace(item, "")
請注意,沒有必要事先檢查item
是否在punctuations
中,如果未找到搜索字符串, replace
不執行任何操作。
(這個 function 讀取一個字符串並檢查它,這個字符串是否具有列表中存在的標點符號(punctuation_chars)然后它將用空字符串替換標記,所以在 function 完成任務后它將返回一個沒有標點符號的字符串)
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation (word):
new_word = ""
for w in word:
if w in punctuation_chars :
y= w.replace(w,"")
new_word = new_word+y
else:
new_word = new_word+w
return new_word
def strip_punctuation(x):
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
for char in x:
if char in punctuation_chars:
x=x.replace(char, ' ')
x=x.replace(' ','')
return x
print(strip_punctuation('he.llo,'))
試試這個,我確保消除字符串中的標點符號
我認為一切都不同......但不要使用替換:
def strip_punctuation(x):
palabra = ""
for chr in x:
if chr not in punctuation_chars:
palabra += chr
return palabra
更一致。 和小。
def strip_punctuation(x):
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
for ch in punctuation_chars:
x=x.replace(ch,"")
return x
這將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.