在文本中查找指定位置的单词
有没有更优雅的方式 (符合Python风格 + 有效) 来查找特定位置的单词呢?
FIRST_WORD = re.compile(r'^(\w+)', re.UNICODE)
LAST_WORD = re.compile(r'(\w+)$', re.UNICODE)
def _get_word(self, text, position):
"""
Get word on given position
"""
assert position >= 0
assert position < len(text)
# get second part of word
# slice string and get first word
match = FIRST_WORD.search(text[position:])
assert match is not None
postfix = match.group(1)
# get first part of word, can be empty
# slice text and get last word
match2 = LAST_WORD.search(text[:position])
if match2 : prefix = match2.group(1)
else : prefix = ''
return prefix + postfix
# | 21.
>>> _get_word("Hello, my name is Earl.", 21)
Earl
>>> _get_word("Hello, my name is Earl.", 20)
Earl
谢谢
3 个回答
0
下面的解决方案是为了获取给定位置周围的字母字符:
def get_word(text, position):
if position < 0 or position >= len(text):
return ''
str_list = []
i = position
while text[i].isalpha():
str_list.insert(0, text[i])
i -= 1
i = position + 1
while text[i].isalpha():
str_list.append(text[i])
i += 1
return ''.join(str_list)
以下是一个测试案例:
get_word("Hello, my name is Earl.", 21) # 'Earl'
get_word("Hello, my name is Earl.", 20) # 'Earl'
我觉得在这里用 split
函数把文本分成单词并不是个好主意,因为位置对这个问题来说非常重要。如果文本中有连续的空格,使用 split
函数可能会引发一些麻烦。
0
在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码有bug,或者是使用的工具和环境设置不对。解决这些问题的第一步就是要仔细检查代码,看看有没有拼写错误、语法错误或者逻辑错误。
另外,了解你使用的编程语言的基本规则和特性也很重要。每种语言都有自己的语法,就像每种语言都有自己的语法规则一样。如果不熟悉这些规则,就容易出错。
有时候,查阅相关的文档或者在网上搜索解决方案也能帮助我们找到问题的根源。很多时候,其他人也遇到过类似的问题,他们可能已经分享了解决方案。
总之,遇到问题时,保持冷静,逐步排查,通常都能找到解决办法。
import string
s = "Hello, my name is Earl."
def get_word(text, position):
_, _, start = text[:position].rpartition(' ')
word,_,_ = text[position:].partition(' ')
return start+word
print get_word(s, 21).strip(string.punctuation)
1
这是我会做的:
s = "Hello, my name is Earl."
def get_word(text, position):
words = text.split()
characters = -1
for word in words:
characters += len(word)
if characters > = position:
return word
>>> get_word(s, 21)
Earl.
去掉标点符号可以用 ''.strip()
,或者用正则表达式,或者用一些比较简单的方法,比如
for c in word:
final += c if c.lower() in 'abcdefghijklmnopqrstuvwxyz'