【问题标题】:Is there a shorter and/or more efficient way to utilize arrays in conditional statements? (in this case the "if" statement)有没有更短和/或更有效的方法在条件语句中利用数组? (在这种情况下是“if”语句)
【发布时间】:2021-03-19 03:30:00
【问题描述】:
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 英里长的代码。是否有另一种方法可以使这段代码更短和/或更高效?

【问题讨论】:

  • 通过text[(character + 1) and (character - 1)] 对字符串进行索引不是它的工作原理。

标签: python arrays performance if-statement conditional-statements


【解决方案1】:

题中代码的物理意义是,如果前后都没有元音,则进行计数,也就是说,任何连续的元音都应该被认为是一个计数。 因此,我们可以高效地编写您的代码并获得相同的结果:

open("TEXT FILE PATH", "r") as text:
    text = text.read()
    count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))

在正则表达式[aeiouAEIOU](?![aeiouAEIOU])中,它选择列表中的任何元音,以防该元音后面没有另一个元音。然后,我们通过函数len()得到它们的数量

示例文本neat retreat

import re
text='neat retreat'
count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))
print(count)

输出:

3

更多校准

import re
text='retreat'
count=len(re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',text))
print(count)

输出

2

【讨论】:

  • 这将匹配一对元音的第二个元音,但 OP 不想要。
  • 也许在(?<![aeiouAEIOU])[aeiouAEIOU](?![aeiouAEIOU])后面加个负面的表情?
  • @wwii 我们需要计数,而不是获取字母本身,所以结果是一样的。
  • @Thierry 我添加了一个示例。如果您通过文本示例解释您的评论,我将不胜感激。
  • OP 在他的问题中给出的最后一个工作示例表明他想要计算既不在元音之前也不在元音之后的元音。在您的示例中,只有“retreat”中的第一个“e”才能满足这些条件。
【解决方案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)

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 2020-11-17
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多