我撰寫了一些代碼來幫助我的 GCSE 修訂(16 歲時在英國進行的考試),它將字串轉換為每個單詞的第一個字母,但保留其他所有內容。(即單詞末尾的特殊字符、大寫等...)
例如:
如果我輸入>>> "These are some words (now they're in brackets!)"
我希望它輸出>>> "T a s w (n t i b!)"
我覺得雖然必須有比我的類似“if”陳述句字串更簡單的方法來做到這一點......作為參考,我對python相當陌生,但我無法在線找到答案。提前致謝!
代碼:
line = input("What text would you like to memorise?\n")
words = line.split()
letters=''
spec_chars=[
'(',')',',','.','“','”','"',"‘","’","'",'!','?','?','?','…'
]
for word in words:
if word[0] in spec_chars:
if word[-1] in spec_chars:
if word[-2] in spec_chars:
if word[1] in spec_chars:
letters = word[0] word[1] word[2] word[-2] word[-1] " "
else:
letters = word[0] word[1] word[-2] word[-1] " "
else:
if word[1] in spec_chars:
letters = word[0] word[1] word[2] word[-1] " "
else:
letters = word[0] word[1] word[-1] " "
else:
if word[1] in spec_chars:
letters = word[0] word[1] word[2] " "
else:
letters = word[0] word[1] " "
else:
if word[-1] in spec_chars:
if word[-2] in spec_chars:
letters = word[0] word[-2] word[-1] " "
else:
letters = word[0] word[-1] " "
else:
letters = word[0] " "
output=("".join(letters))
print(output)
uj5u.com熱心網友回復:
這是另一種選擇。我們保留除撇號以外的所有標點符號,并且只保留遇到的第一個字母。
words = "These are some words (now they're in brackets!)"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzé'"
output = []
for word in words.split():
output.append( '' )
found = False
for i in word:
if i in alphabet:
if not found:
found = True
output[-1] = i
else:
output[-1] = i
print(' '.join(output))
輸出:
T a s w (n t i b!)
uj5u.com熱心網友回復:
現在這可能有點壓倒性,但我仍然想指出一個解決方案,它允許使用正則運算式提供更簡潔的解決方案,因為它在如何解決此類問題方面非常具有指導意義。
TL;DR:可以在一行中完成
import re
' '.join(re.sub(r"(\w)[\w']*\w", r'\1', word) for word in text.split())
如果您在使用后單獨查看單詞.split(),您需要做的基本上是洗掉每個單詞中出現的第一個字母之后的所有字母(和單詞內部撇號)。
[
'"These', # remove 'hese'
'are', # 're'
'some', # 'ome'
'words', # 'ords'
'(now', # 'ow'
"they're", # "hey're"
'in', # 'n'
'brackets!)"' # 'rackets'
]
另一種考慮它的方法是找到由以下組成的序列
- 一封信
x - 1 個或多個字母的序列
并將序列替換為x. 例如,在 中'"These',替換'These'為'T'。到達'"T'; 在brackets!)", 替換'brackets'為'b'等
在正則運算式語法中,這變為:
(\w): 一個字母由 匹配\w,但我們想稍后參考它,所以我們需要把它放在一個組中——因此是括號。- 1 個或多個(用 表示
)字母的序列是\w。我們還想包括撇號,所以我們需要一個由 表示的類[],即 ,[\w']這意味著“匹配一個或多個字母或撇號的實體”。
要替換/替換與我們使用的模式匹配的子字串re.sub(pattern, replacement, string)。在替換字串中,我們可以告訴它使用參考插入我們之前定義的組\1。
把它們放在一起:
# import the re module
import re
# define the regular expression
pattern = r"(\w)[\w'] "
# some test data
texts = ["\"These are some words (now they're in brackets!)\"",
"?Qué es lo mejor asignatura? '(?No es dibujo!!)'",
"The kids' favourite teacher"]
# testing the pattern
for text in texts:
words = text.split()
print(text)
print(' '.join(re.sub(pattern, r'\1', word) for word in words))
print()
結果:
"These are some words (now they're in brackets!)"
"T a s w (n t i b!)"
?Qué es lo mejor asignatura? '(?No es dibujo!!)'
?Q e l m a? '(?N e d!!)'
The kids' favourite teacher
T k f t
要包含詞尾撇號,請將模式修改為
pattern = r"(\w)[\w']*\w"
所以字母撇號序列必須以字母結尾。換句話說,我們現在匹配
- 由一個字母組成的組
(\w),后跟 - 零個或多個(由 表示
*)字母或撇號實體,以及 - 一封信
\w。
結果和上面完全一樣,只是最后一句變成了“T k' f t”。
uj5u.com熱心網友回復:
下面的代碼對我來說作業正常。
在這里,我只是檢查給定句子的每個單詞的左端和右端。
如果有任何澄清,請告訴我。
words = "?Qué es lo mejor asignatura? '(?No es dibujo!!)'"
spec_chars = ['(', ')', ',', '.', '“', '”', '"', "‘",
"’", "'", '!', '?', '?', '?', '…']
s_lst = words.split(' ')
tmp, rev_tmp = '', ''
for i in range(len(s_lst)):
for l in s_lst[i]:
if l in spec_chars:
tmp = l
else:
tmp = l
for j in s_lst[i][::-1]:
if j in spec_chars:
rev_tmp = j
else:
tmp = rev_tmp[::-1]
break
s_lst[i] = tmp
tmp = ''
rev_tmp = ''
break
print(' '.join(s_lst))
uj5u.com熱心網友回復:
由于您提到您處于入門級,您可以使用 for 回圈來簡化您的 if 陳述句。它并不完美,但可以解決您提出的問題。
line = input("What text would you like to memorise?\n")
words = line.split()
spec_chars=['(',')',',','.','“','”','"',"‘","’","'",'!','?','?','?','…']
letters=''
for word in words:
letters =word[0]
if word[0] in spec_chars:
letters =word[1]
elif word[-2] in spec_chars:
letters =word[-2] word[-1]
elif word[-1] in spec_chars:
letters =word[-1]
print(letters)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465166.html
