开发者

nth word in a text

how can I find the nth word in a text.

example:

my_txt("hello to you all" , 3)

all

I don't wanna开发者_C百科 use any built in function ...and this is not a homework :D


The obvious way to do it is:

"hello to you all".split()[3]

The 80's way to do it is - that is, you have to walk the text, keeping note of the state of things you have found - it can become better than this, probably, but that is the idea. Perceive one has to use a lot o "built-in" functions either way. I just avoid the ones that make it straight like above.

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


OK you asked for this. You need a "split into words" function. Here it is. Assumes that "words" are delimited by whitespace.

No built-in functions, no imported anythings, no methods of built-in types, not even any panty-waist stuff like +=. And it's tested.

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


Since everything is a built in function in one way or another, I'm gonna ignore your claim to not want to use built in functions.

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

Main drawback with this is that you'll get punctuation included. I leave it as exercise to figure out how to get rid of that. :)


First let me say that I absolutely agree with the comments and the other answer, not using built in functions is stupid. That being said, I found that attempting to write this code using as few built in function calls to be an interesting challenge, so I'll post what I came up with anyways.

def my_txt(txt, n, i=0):
    if n == 1:
        r = ""
        s = 0
        for c in txt:
            if s >= i:
                if c == " ":
                    return r
                r += c
            s += 1
    while txt[i] != " ":
        i += 1
    return my_txt(txt, n - 1, i + 1)

my_txt("hello to you all", 3) # returns 'you'

My self inflicted rules: no slices, comprehensions, generators, or built in function calls.

This code will horribly fail when attempting to get the last word (unless there is a trailing space) or for any n out of the range of words.


obviously that's not without "built in functions" but it won't give error, no matter how hard u try :)

def my_text(string, integer=None):
  try:
    integer = int(integer)
  except ValueError:
    return 'enter a number'
  else:
    try:
      return string.split()[integer - 1]
    except IndexError:
      string = string.split()
      return f"text contains only {len(string)} word"

def inp():
  try:
    return int(input('Which word you need? ex: 1,2,3 etc.: '))
  except ValueError:
    return 'Enter number please'

print(my_text(input('Enter text here:  '), inp()))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜