type-of-python做業-判斷字符串是否屬於迴文須要忽略其中的標點、空格與大小寫

type-of-python做業

做業練習:要想檢查文本是否屬於迴文須要忽略其中的標點、空格與大小寫。例如,「Rise to vote, sir.」是一段迴文文本,可是咱們現有的程序不會這麼認爲。你能夠改進上面的程序以使它可以識別

這段迴文嗎?html

**注:**本文中用的python版本爲3.70,編譯器:PyCharm edupython

參考的網站網站一網站二網站三網站四:多謝前輩的指導!!!網站

import string
import re

# 將字符串反轉,並返回
def reverse(text):
    return text[::-1]

# 檢測反轉後的字符串和最開始的字符串是否相同
def is_palindrome(text):
    text0 = clear(text)
    return text0 == reverse(text0)

# 將數據的字符串中的空白字符和標點符號
def clear(text):
    # 去掉字符串中的空白字符
    text1 = re.sub('\s','',text)
    bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    # 此爲中文標點符號
    punc = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛「」„‟…‧﹏."
    # string.punctuation 此爲英文標點符號
    mark=''.join([punc,string.punctuation])
    bytes1 = mark.encode(encoding='utf-8',errors='strict')
    bytestr = text1.encode(encoding='utf-8',errors='strict')
    # 去掉字符串中的標點符號
    return (bytestr.translate(bytes_tabtrans,bytes1)).decode("utf-8")

# 從客戶端輸入被檢測的字符串
something = input("Enter text: ")
if is_palindrome(something):
    print("Yes, it is a palindrome")
else:
    print("No,it is not a palindrome" )

博客有哪裏寫的不對的地方,多謝留言評論url

相關文章
相關標籤/搜索