1

私はこの割り当てを持っています:

smallnr(x)数値を受け取り、 がその間の整数である場合、数値の名前を返す関数を作成しxます。それ以外の場合は、単純に文字列として返します。x06x

私は次のことをしました:

def smallnr(x):
    if x>6:
        return str(x)
    else:
        lst=['zero','one','two','three','four','five','six']
        return (lst[x])

それはうまくいきますが、今はこれをしなければなりません:

smallnrパート a の関数を使用してconvertsmall(s)、入力としてテキストを受け取り、名前に変換された小さな数字 (0 から 6 までの整数) を含むテキストsを返す 関数を作成します。s例えば、

convertsmall('私には 5 人の兄弟と 2 人の姉妹、合計 7 人の兄弟がいます.') '私には 5 人の兄弟と 2 人の姉妹、合計 7 人の兄弟がいます.'

split()どうにかして使用する必要があることはわかっていますisnumeric()が、すべてをまとめて文字列内の数字だけを変更する方法がわかりません。

何かアドバイス?

4

5 に答える 5

0

したがって、convertsmall関数に渡した文の文字列を取得し、スペースで分割します。これを行うには、文字列を取得して呼び出します.split(' ')(例:'hello world'.split(' ')またはmystring.split(' '))。これにより、次のような分割配列が得られます['hello', 'world']

次に、結果の配列を反復処理して数値または整数を探し、それらを関数に渡して文字列値を取得し、配列内の値を文字列値に置き換える必要があります。

次に、各単語を調べて数値を変換したら、最終的な配列を結合する必要があります。あなたはすることによってこれを行うことができます' '.join(myArray)

于 2012-10-03T23:42:19.983 に答える
0
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 

私はうまくいくと思います

>>> 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.
于 2012-10-03T23:42:39.167 に答える
0

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:]
于 2012-10-04T00:14:31.793 に答える
0
  1. 文を分割する (スペースで)
  2. (分割から) 単語を反復処理します。
  3. 単語が数値の場合、関数の結果に置き換えます
  4. それらをすべて元に戻す
  5. 結果を返す
于 2012-10-03T23:39:26.593 に答える
0

これを行う最も簡単な方法は次のとおりです(私の意見では):

def convertsmall(text):
    return ' '.join(smallnr(int(word)) if word.isdigit() else word for word in text.split())

出力:

>>> convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.')
'I have five brothers and two sisters, 7 siblings altogether.'

これを理解するために、さかのぼってみましょう。

  1. 次を使用して文字列をlist単語に分割しますtext.split()- 引数が渡されない場合、split() は' '(スペース) を区切り文字として使用して文字列を分割します。
  2. smallnr(int(word)) if word.isdigit() else wordsmallnr()- が数値の場合は呼び出しword、そうでない場合は変更せずに返しますword
  3. は文字列であるため、関数に渡す前に をword使用して整数に変換する必要があります。これは整数であると想定されます。int(word)x
  4. フレーズ全体がリスト内包表記であり、それぞれを処理wordtext.split()て新しいリストを生成します。word' '.join(list) を使用して、このリスト内の s をスペースで区切って結合します。

それが明確になることを願っています:)

于 2012-10-04T00:33:32.173 に答える