[英]Is there a shorter and/or more efficient way to utilize arrays in conditional statements? (in this case the “if” statement)
count = 0
vowels = "aeiou"
open("TEXT FILE PATH", "r") as text:
text = text.read()
for character in range(len(text) - 1):
if text[(character + 1) and (character - 1)] not in vowels and text[character] in vowels:
count += 1
在上面的“if 語句”中,我試圖檢查“字符”前面和后面的字符串是否不是元音,同時最小化我的條件的長度,但在 Python 中,這不起作用,而下面的行是。
if text[character] in vowels and text[(character + 1)] not in vowels and text[character - 1] not in vowels:
基本上這個想法不是像上面那行那樣有 3 英里長的代碼。 是否有另一種方法可以使這段代碼更短和/或更高效?
題中代碼的物理意義是,如果前后都沒有元音,則進行計數,也就是說,任何連續的元音都應該被認為是一個計數。 因此,我們可以以有效的方式編寫您的代碼並獲得相同的結果:
open("TEXT FILE PATH", "r") as text:
text = text.read()
count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))
在正則表達式[aeiouAEIOU](?![aeiouAEIOU])
中,它選擇列表中的任何元音,以防該元音后面沒有另一個元音。 然后,我們使用 function len()
得到它們的數量
文本neat retreat
的例子
import re
text='neat retreat'
count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))
print(count)
output:
3
更多的校准
import re
text='retreat'
count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))
print(count)
output
2
您可以創建文本的所有 3-len 部分並使用all()
檢查:
count = 0
vowels = set("aeiou")
text = """All your bases belong to us if you can read this"""
parts = [text[p:p+3] for p in range(len(text)-3)]
# get the total count
count += sum( all(p[k] not in vowels for k in (0,2)) for p in parts)
# or print whats been counted
for p in parts:
if all(p[w] not in vowels for w in [0,2]):
print(p)
print(count)
Output:
All
ll
l y
r b
bas
ses
s b
bel
lon
ng
g t
to
us
if
f y
can
n r
d t
th
19
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.