【发布时间】:2018-07-02 23:59:22
【问题描述】:
给定一个 Python 字符串,我想在给定范围的字符串 sentence 内对给定 word 子字符串的出现进行宽间距。我找不到执行此算法的有效且简洁的方法。
我只想对索引在sentence 字符串的给定范围内的单词进行宽间距,并且单词必须准确(不能被其他单词字符包围,例如字母和数字)。计算单词准确度时会忽略标点符号和其他符号。
到目前为止,我的函数widespace(sentence, word, start = None, end = None): 应该在从start 到end 的给定范围内对给定的word 进行宽间距,但目前它看起来效率很低且冗长。它也无法检测精确的单词匹配并忽略标点符号。
预期结果
- 如果单词在
range(start, end)内,所有出现的单词都会受到影响,也就是说,索引大于或等于start,严格小于end。 - 完全匹配忽略标点符号,但区分大小写。例如,如果要匹配
"omg",它接受"omg!"和"omg,",但不接受被其他单词字符包围的"omg",例如"zomg"或"omgf"- 单词字符可以包括数字、字母、连字符,这是您的偏好。
-
widespace("Foo, Bar, Baz!", "Baz")变为Foo, Bar, B a z!- 索引为 10。
-
widespace("Foo, Foo, Foo!", "Foo")变为F o o, F o o, F o o!- 索引为 0、5、10。
-
widespace("Foo, Foo, Foo!", "Foo", start = 0, end = 2)变为F o o, Foo, Foo!- 索引为 0、5、10。只有第一个(索引 0)受到影响。
-
widespace("Foo, Foo, Foo!", "Foo", start = 0, end = 5)变成F o o, Foo, Foo!就像前面的例子一样- 索引为 0、5、10。只有第一个(索引 0)受到影响,因为第二个与 5 完全匹配,超出了范围。
-
widespace("Foo, Foo, Foo!", "Foo", start = 0, end = 6)变为F o o, F o o, Foo!- 索引为 0、5、10。只有前两个得到匹配。
-
widespace("Mulliganaceous Mulligan, OMG", "Mulligan")应该变成Mulliganaceous M u l l i g a n, OMG"-
"Mulliganaceous"不完全匹配。但是"Mulligan,"算作一个,因为它没有被其他单词字符包围。 - 我目前有
M u l l i g a naceous M u l l i g a n
-
当前代码
到目前为止,我已经可以使用它了,但是代码很长,可能效率低下,并且无法处理完全匹配和标点符号。
def widespace(sentence: str, word: str, start: int = None, end: int = None):
if not start:
start = 0
if not end:
end = len(sentence)
spacedword = " ".join(word)
indices = []
cur = sentence.find(word, start)
# Find all occurrences of the word
while cur >= 0 and cur < end + len(word) - 1:
# Add to list
indices.append(cur)
# Next occurrence
cur = cur + len(word)
cur = sentence.find(word, cur, end + len(word) - 1)
print("\t" + str(indices)) # To check indices
# Replace word with spaced-out word
while len(indices) > 0:
index = indices.pop()
sa = sentence[:index]
sb = sentence[index:index + len(word)]
sc = sentence[index + len(word):]
sb = sb.replace(word, spacedword)
sentence = sa + sb + sc
return sentence
如何在 Python 的某个范围内加宽给定单词(完全匹配,忽略标点符号)?满足所有期望的有效解决方案是首选,尽管我对结果非常灵活。
【问题讨论】:
-
您的第二个示例的结束范围应该是 5 而不是 4?
-
谢谢我的坏。我只是在编辑问题以使其更清楚。
标签: python string whitespace