gpt4 book ai didi

php - 在 PHP 中将单词转换为数字

转载 作者:IT王子 更新时间:2023-10-29 00:00:44 25 4
gpt4 key购买 nike

我正在尝试将写为单词的数值转换为整数。例如,“iPhone有二十三万七百八十三个应用程序”会成为“iPhone 作为 230783 个应用程序”

在我开始编码之前,我想知道是否存在任何用于此转换的函数/代码。

最佳答案

有很多页面讨论从数字到单词的转换。反方向没有那么多。我能找到的最好的是 Ask Yahoo 上的一些伪代码。见 http://answers.yahoo.com/question/index?qid=20090216103754AAONnDz一个不错的算法:

Well, overall you are doing two things: Finding tokens (words that translates to numbers) and applying grammar. In short, you are building a parser for a very limited language.

The tokens you would need are:

POWER: thousand, million, billion
HUNDRED: hundred
TEN: twenty, thirty... ninety
UNIT: one, two, three, ... nine,
SPECIAL: ten, eleven, twelve, ... nineteen

(drop any "and"s as they are meaningless. Break hyphens into two tokens. That is sixty-five should be processed as "sixty" "five")

Once you've tokenized your string, move from RIGHT TO LEFT.

  1. Grab all the tokens from the RIGHT until you hit a POWER or the whole string.

  2. Parse the tokens after the stop point for these patterns:

    SPECIAL
    TEN
    UNIT
    TEN UNIT
    UNIT HUNDRED
    UNIT HUNDRED SPECIAL
    UNIT HUNDRED TEN
    UNIT HUNDRED UNIT
    UNIT HUNDRED TEN UNIT

    (This assumes that "seventeen hundred" is not allowed in this grammar)

    This gives you the last three digits of your number.

  3. If you stopped at the whole string you are done.

  4. If you stopped at a power, start again at step 1 until you reach a higher POWER or the whole string.

关于php - 在 PHP 中将单词转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1077600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com