輸入:
string = "My dear adventurer, do you understand the nature of the given discussion?"
預期輸出:
string = 'My dear ##########, do you ########## the nature ## the given ##########?'
如何將字串中的第三個單詞替換為該單詞的 # 長度等效項,同時避免計算字串中的特殊字符,例如撇號(')、引號(“)、句號(.)、逗號(, )、感嘆號 (!)、問號 (?)、冒號 (:) 和分號 (;)。
我采用了將字串轉換為元素串列的方法,但發現很難過濾掉特殊字符并將單詞替換為 # 等效項。有沒有更好的方法來解決它?
uj5u.com熱心網友回復:
我解決了它:
s = "My dear adventurer, do you understand the nature of the given discussion?"
def replace_alphabet_with_char(word: str, replacement: str) -> str:
new_word = []
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for c in word:
if c in alphabet:
new_word.append(replacement)
else:
new_word.append(c)
return "".join(new_word)
every_nth_word = 3
s_split = s.split(' ')
result = " ".join([replace_alphabet_with_char(s_split[i], '#') if i % every_nth_word == every_nth_word - 1 else s_split[i] for i in range(len(s_split))])
print(result)
輸出:
My dear ##########, do you ########## the nature ## the given ##########?
uj5u.com熱心網友回復:
有更有效的方法可以解決這個問題,但我希望這是最簡單的!
我的做法是:
- 將句子拆分為單詞串列
- 使用它,列出每三個單詞。
- 從中洗掉不需要的字符
- 將原始字串中的第三個單詞替換為單詞長度的 # 倍。
這是代碼(在評論中解釋):
# original line
line = "My dear adventurer, do you understand the nature of the given discussion?"
# printing original line
print(f'\n\nOriginal Line:\n"{line}"\n')
# printing somehting to indicate that next few prints will be for showing what is happenning after each lone
print('\n\nStages of parsing:')
# splitting by spaces, into list
wordList = line.split(' ')
# printing wordlist
print(wordList)
# making list of every third word
thirdWordList = [wordList[i-1] for i in range(1,len(wordList) 1) if i%3==0]
# pritning third-word list
print(thirdWordList)
# characters that you don't want hashed
unwantedCharacters = ['.','/','|','?','!','_','"',',','-','@','\n','\\',':',';','(',')','<','>','{','}','[',']','%','*','&',' ']
# replacing these characters by empty strings in the list of third-words
for unwantedchar in unwantedCharacters:
for i in range(0,len(thirdWordList)):
thirdWordList[i] = thirdWordList[i].replace(unwantedchar,'')
# printing third word list, now without punctuation
print(thirdWordList)
# replacing with #
for word in thirdWordList:
line = line.replace(word,len(word)*'#')
# Voila! Printing the result:
print(f'\n\nFinal Output:\n"{line}"\n\n')
希望這可以幫助!
uj5u.com熱心網友回復:
以下作業并且不使用正則運算式
special_chars = {'.','/','|','?','!','_','"',',','-','@','\n','\\'}
def format_word(w, fill):
if w[-1] in special_chars:
return fill*(len(w) - 1) w[-1]
else:
return fill*len(w)
def obscure(string, every=3, fill='#'):
return ' '.join(
(format_word(w, fill) if (i 1) % every == 0 else w)
for (i, w) in enumerate(string.split())
)
以下是一些示例用法
In [15]: obscure(string)
Out[15]: 'My dear ##########, do you ########## the nature ## the given ##########?'
In [16]: obscure(string, 4)
Out[16]: 'My dear adventurer, ## you understand the ###### of the given ##########?'
In [17]: obscure(string, 3, '?')
Out[17]: 'My dear ??????????, do you ?????????? the nature ?? the given ???????????'
uj5u.com熱心網友回復:
在一些正則運算式的幫助下。評論中的解釋。
import re
imp = "My dear adventurer, do you understand the nature of the given discussion?"
every_nth = 3 # in case you want to change this later
out_list = []
# split the input at spaces, enumerate the parts for looping
for idx, word in enumerate(imp.split(' ')):
# only do the special logic for multiples of n (0-indexed, thus 1)
if (idx 1) % every_nth == 0:
# find how many special chars there are in the current segment
len_special_chars = len(re.findall(r'[.,!?:;\'"]', word))
# ^ add more special chars here if needed
# subtract the number of special chars from the length of segment
str_len = len(word) - len_special_chars
# repeat '#' for every non-special char and add the special chars
out_list.append('#'*str_len word[-len_special_chars] if len_special_chars > 0 else '')
else:
# if the index is not a multiple of n, just add the word
out_list.append(word)
print(' '.join(out_list))
uj5u.com熱心網友回復:
正則運算式和字串操作的混合
import re
string = "My dear adventurer, do you understand the nature of the given discussion?"
new_string = []
for i, s in enumerate(string.split()):
if (i 1) % 3 == 0:
s = re.sub(r'[^\.:,;\'"!\?]', '#', s)
new_string.append(s)
new_string = ' '.join(new_string)
print(new_string)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448814.html
上一篇:如何用點、感嘆號或問號連接字串?
