德州第N个字

2024-06-02 06:53:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能在课文中找到第n个单词。

示例:

my_txt("hello to you all" , 3)

all

我不想使用任何内置函数…这不是家庭作业:D


Tags: to函数txtyou示例hellomyall
3条回答

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

没有内置函数,没有导入的任何东西,没有内置类型的方法,甚至没有像+=这样的裤腰。而且已经测试过了。

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']
>>>

因为所有都是以某种方式内置的函数,所以我将忽略您不想使用内置函数的声明。

def my_txt(text, n):
    return text.split()[n]

这样做的主要缺点是会包含标点符号。我把它当作练习来解决这个问题。:)

显而易见的做法是:

"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")

相关问题 更多 >