changing a word in a string?
题
I have this assignment:
Write a function
smallnr(x)
that takes a numberx
and ifx
is an integer between0
and6
it returns the name of the number, otherwise it simply returnsx
as a string.
I did the following:
def smallnr(x):
if x>6:
return str(x)
else:
lst=['zero','one','two','three','four','five','six']
return (lst[x])
and that works, but now I have to do this:
Using the function
smallnr
from part a, write a functionconvertsmall(s)
that takes as input a texts
and returns the texts
with small numbers (integers between 0 and 6) converted to their names. For example,convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.') 'I have five brothers and two sisters, 7 siblings altogether.'
I know I need to use split()
and isnumeric()
somehow, but I can't figure out how to put it all together and change just the numbers within the string.
Any advice?
解决方案
Here's the easiest way to do this (in my opinion):
def convertsmall(text):
return ' '.join(smallnr(int(word)) if word.isdigit() else word for word in text.split())
Output:
>>> convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.')
'I have five brothers and two sisters, 7 siblings altogether.'
To understand this, let's go backwards:
- Divide the string into a
list
of words usingtext.split()
- When no argument is passed, split() divides the string using' '
(space) as delimiter. smallnr(int(word)) if word.isdigit() else word
- Callssmallnr()
ifword
is a number, otherwise returnsword
unchanged.- Since
word
is a string, we need to convert it into an integer usingint(word)
before passing it to your function, which assumesx
to be an integer. - The entire phrase is a list comprehension, which processes each
word
intext.split()
to product a new list. We join theword
s in this list together separated by spaces, using ' '.join(list).
Hope that makes it clear :)
其他提示
- Split the sentence (on the space)
- Iterate through the words (from the split)
- if the word isnumeric replace it with the result of the function
- join them all back together
- return the result
So you want to take your sentence string which you pass into the convertsmall function and split it by spaces. You can do this by taking your string and calling .split(' ')
(eg. 'hello world'.split(' ')
or mystring.split(' ')
). This'll give you a split array like ['hello', 'world']
Then you need to iterate through the resulting array and look for numbers or integers and then pass them to your function and get the string value and replace the value in the array with the string value.
You then need to join up the final array once you've gone through each word and converted the numbers. You can do this by doing ' '.join(myArray)
Solution based on regex rather than split():
def convertsmall(s):
out = ''
lastindex=0
for match in re.finditer("\\b(\\d+)\\b", s):
out += s[lastindex:match.start()]
out += smallnr(int(match.group()))
lastindex = match.end()
return out + s[lastindex:]
d={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six'}
parts = my_string.split() #split into words
new_parts = [d[p] if p in d else p for p in parts] #list comprehension to replace if possible
print " ".join(parts) #rejoin
I think will work
>>> mystring = 'I have 5 brothers and 2 sisters, 7 siblings altogether.'
>>> parts = mystring.split() #split into words
>>> d={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six'}
>>> new_parts = [d[p] if p in d else p for p in parts] #list comprehension to replace if possible
>>> print " ".join(new_parts) #rejoin
I have five brothers and two sisters, 7 siblings altogether.