如何在文本中找到第 n 个单词。
例子:
my_txt("hello to you all" , 3)
all
我不想使用任何内置函数......这不是作业:D
最佳答案
显而易见的方法是:
"hello to you all".split()[3]
80 年代的做法是——也就是说,你必须遍历文本,注意你发现的事物的状态——它可能会变得比这更好,但这就是想法。无论哪种方式,人们都必须使用很多“内置”功能。我只是避免像上面那样直截了当的那些。
def my_txt(text, target):
count = 0
last_was_space = False
start = end = 0
for index, letter in enumerate(text):
if letter.isspace():
if not last_was_space:
end = index
last_was_space = True
elif last_was_space:
last_was_space = False
count += 1
if count > target:
return text[start:end]
elif count == target:
start = index
if count == target:
return text[start:].strip()
raise ValueError("Word not found")
关于python - 文本中的第 n 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495176/