第n个单词在文本中

use*_*225 0 python string

如何在文本中找到第n个单词.

例:

my_txt("hello to you all" , 3)

all
Run Code Online (Sandbox Code Playgroud)

我不想使用任何内置功能......这不是作业:D

jsb*_*eno 11

显而易见的方法是:

"hello to you all".split()[3]
Run Code Online (Sandbox Code Playgroud)

80年代的方法是 - 也就是说,你必须走完文本,记下你发现的事情的状态 - 可能会比这更好,但这就是想法.Perceive必须使用很多"内置"功能.我只是避免那些像上面一样直的.

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")
Run Code Online (Sandbox Code Playgroud)

  • @pst:如果这会让你头疼,你最好不要阅读`str.split`的真实C实现:-) (2认同)

Joh*_*hin 2

好吧,你要求这个。您需要一个“拆分成单词”的功能。这里是。假设“单词”由空格分隔。

没有内置函数,没有导入任何东西,没有内置类型的方法,甚至没有像+=. 并且已经过测试。

C:\junk>\python15\python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def mysplit(s):
...     words = []
...     inword = 0
...     for c in s:
...         if c in " \r\n\t": # whitespace
...             inword = 0
...         elif not inword:
...             words = words + [c]
...             inword = 1
...         else:
...             words[-1] = words[-1] + c
...     return words
...
>>> mysplit('')
[]
>>> mysplit('x')
['x']
>>> mysplit('foo')
['foo']
>>> mysplit('  foo')
['foo']
>>> mysplit('  foo    ')
['foo']
>>> mysplit('\nfoo\tbar\rzot ugh\n\n   ')
['foo', 'bar', 'zot', 'ugh']
>>>
Run Code Online (Sandbox Code Playgroud)