在 php 中将单词转换为数字 II

2024-05-14

这里有一个很棒的功能在 PHP 中将单词转换为数字 https://stackoverflow.com/questions/1077600/converting-words-to-numbers-in-php来自埃尔约博。 但我有一个问题,字符串必须以书面数字开头。 如何转换例如“iPhone 有二十三万、七百八十三个应用程序”?

解释的功能:

function wordsToNumber($data) {
// Replace all number words with an equivalent numeric value
$data = strtr(
    $data,
    array(
        'zero'      => '0',
        'a'         => '1',
        'one'       => '1',
        'two'       => '2',
        'three'     => '3',
        'four'      => '4',
        'five'      => '5',
        'six'       => '6',
        'seven'     => '7',
        'eight'     => '8',
        'nine'      => '9',
        'ten'       => '10',
        'eleven'    => '11',
        'twelve'    => '12',
        'thirteen'  => '13',
        'fourteen'  => '14',
        'fifteen'   => '15',
        'sixteen'   => '16',
        'seventeen' => '17',
        'eighteen'  => '18',
        'nineteen'  => '19',
        'twenty'    => '20',
        'thirty'    => '30',
        'forty'     => '40',
        'fourty'    => '40', // common misspelling
        'fifty'     => '50',
        'sixty'     => '60',
        'seventy'   => '70',
        'eighty'    => '80',
        'ninety'    => '90',
        'hundred'   => '100',
        'thousand'  => '1000',
        'million'   => '1000000',
        'billion'   => '1000000000',
        'and'       => '',
    )
);

// Coerce all tokens to numbers
$parts = array_map(
    function ($val) {
        return floatval($val);
    },
    preg_split('/[\s-]+/', $data)
);

$stack = new SplStack; // Current work stack
$sum   = 0; // Running total
$last  = null;

foreach ($parts as $part) {
    if (!$stack->isEmpty()) {
        // We're part way through a phrase
        if ($stack->top() > $part) {
            // Decreasing step, e.g. from hundreds to ones
            if ($last >= 1000) {
                // If we drop from more than 1000 then we've finished the phrase
                $sum += $stack->pop();
                // This is the first element of a new phrase
                $stack->push($part);
            } else {
                // Drop down from less than 1000, just addition
                // e.g. "seventy one" -> "70 1" -> "70 + 1"
                $stack->push($stack->pop() + $part);
            }
        } else {
            // Increasing step, e.g ones to hundreds
            $stack->push($stack->pop() * $part);
        }
    } else {
        // This is the first element of a new phrase
        $stack->push($part);
    }

    // Store the last processed part
    $last = $part;
}

return $sum + $stack->pop();
}

嗯..我必须承认..这对我个人来说很有趣!无论如何...这是代码...您可以在这里测试它:http://www.eyerollweb.com/str2digits/ http://www.eyerollweb.com/str2digits/

这是代码本身:

<?php

//The Test string
$str = "two hundred thousand six hundred and two";

$numbers = array(
    'zero' => 0,
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4,
    'five' => 5,
    'six' => 6,
    'seven' => 7,
    'eight' => 8,
    'nine' => 9,
    'ten' => 10,
    'eleven' => 11,
    'twelve' => 12,
    'thirteen' => 13,
    'fourteen' => 14,
    'fifteen' => 15,
    'sixteen' => 16,
    'seventeen' => 17,
    'eighteen' => 18,
    'nineteen' => 19,
    'twenty' => 20,
    'thirty' => 30,
    'forty' => 40,
    'fourty' => 40, // common misspelling
    'fifty' => 50,
    'sixty' => 60,
    'seventy' => 70,
    'eighty' => 80,
    'ninety' => 90,
    'hundred' => 100,
    'thousand' => 1000,
    'million' => 1000000,
    'billion' => 1000000000);

//first we remove all unwanted characters... and keep the text
$str = preg_replace("/[^a-zA-Z]+/", " ", $str);

//now we explode them word by word... and loop through them
$words = explode(" ", $str);

//i devide each thousands in groups then add them at the end
//For example 2,640,234 "two million six hundred and fourty thousand two hundred and thirty four"
//is defined into 2,000,000 + 640,000 + 234

//the $total will be the variable were we will add up to
$total = 1;

//flag to force the next operation to be an addition
$force_addition = false;

//hold the last digit we added/multiplied
$last_digit = null;

//the final_sum will be the array that will hold every portion "2000000,640000,234" which we will sum at the end to get the result
$final_sum = array();

foreach ($words as $word) {

    //if its not an and or a valid digit we skip this turn
    if (!isset($numbers[$word]) && $word != "and") {
        continue;
    }

    //all small letter to ease the comparaison
    $word = strtolower($word);

    //if it's an and .. and this is the first digit in the group we set the total = 0 
    //and force the next operation to be an addition
    if ($word == "and") {
        if ($last_digit === null) {
            $total = 0;
        }
        $force_addition = true;
    } else {
        //if its a digit and the force addition flag is on we sum
        if ($force_addition) {
            $total += $numbers[$word];
            $force_addition = false;
        } else {
            //if the last digit is bigger than the current digit we sum else we multiply
            //example twenty one => 20+1,  twenty hundred 20 * 100
            if ($last_digit !== null && $last_digit > $numbers[$word]) {
                $total += $numbers[$word];
            } else {
                $total *= $numbers[$word];
            }
        }
        $last_digit = $numbers[$word];

        //finally we distinguish a group by the word thousand, million, billion  >= 1000 ! 
        //we add the current total to the $final_sum array clear it and clear all other flags...
        if ($numbers[$word] >= 1000) {
            $final_sum[] = $total;
            $last_digit = null;
            $force_addition = false;
            $total = 1;
        }
    }



}

// there is your final answer !
$final_sum[] = $total;
print "Final Answer: " . array_sum($final_sum) . "\n";

?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 php 中将单词转换为数字 II 的相关文章

  • 无法与站点通信以检查致命错误

    无法与站点通信以检查致命错误 因此 PHP 更改已恢复 您需要通过其他方式上传 PHP 文件更改 例如使用 SFTP 有什么解决办法 我正在 WordPress 中编辑头文件 遇到这个问题 尝试这个 我有同样的问题并决定调查一下 更改 wp
  • 如何显示 PHP 对象

    我有这样的代码 dataRecord1 client gt GetRecord token table filter echo pre print r dataRecord1 echo pre foreach dataRecord1 gt
  • 如何让 Laravel“确认”验证器将错误添加到确认字段?

    默认情况下 Laravel 确认 验证器将错误消息添加到原始字段 而不是通常包含确认值的字段 password gt required confirmed min 8 是否有任何简单的方法来扩展验证器或使用一些技巧来强制它始终在确认字段而不
  • file_get_contents,HTTP 请求失败

    我尝试使用以下方式从另一个网站获取内容file get contents但我总是收到 无法打开流 HTTP 请求失败 allow url fopen 已打开 并且我已经在防火墙关闭的情况下进行了测试 但还是会出现这种情况 请问还有什么原因呢
  • Facebook 扩展权限

    更新2 好的 通过更改使其 有点 工作 loginUrl facebook gt getLoginUrl array canvas gt 1 fbconnect gt 0 req perms gt publish stream next g
  • Ajax 与 chrome 扩展

    我将 url 发送到 chrome 扩展中的 php 文件 并需要获得响应 但不起作用 清单 json name Get pages source version 1 0 manifest version 2 description Get
  • 提交简单 PHP 表单时出现禁止错误

    我有一个不复杂的问题 这似乎比应有的更复杂 我有一个简单的表单 用于向网站添加内容 有些字段需要输入html 然而 当您在表单的不同部分输入某些 html 元素时 它会认为它讨厌您并抛出禁止的 403 错误 这是下面的表格
  • PHP FTP_PUT 上传到目录

    我正在自学PHP 一本名为 PHP完全参考 PHP5 2 的书 我目前正在使用第 11 章 FTP 上传 删除 makedir 等 但遇到了一些本书未涵盖的问题 根据我的教科书 这是上传到服务器的简单代码 connect ftp conne
  • 使用 PHP 创建、编辑和删除 crontab 作业?

    是否可以使用 PHP 创建 编辑和删除 crontab 作业 我知道如何列出 Apache 用户当前的 crontab 作业 output shell exec crontab l echo output 但是如何使用 PHP 添加 cro
  • 如何接收发送到 twilio 号码的短信

    我在 twilio 创建了一个免费帐户 用于通过我的网站发送短信 注册后 我得到了一个 twilio 号码 例如 XXX XXX XXXX 我可以向手机号码发送消息 但我不知道如何使用这个 twilio 号码接收短信 请帮我解决这个问题 T
  • php/symfony/doctrine 内存泄漏?

    我在使用 symfony 1 4 和原则 1 2 将对象批量插入数据库时 遇到问题 我的模型有一种称为 Sector 的对象 每个对象都有多个 Cupo 类型的对象 通常范围从 50 到 200000 这些物体非常小 只是一个短标识符字符串
  • 将 jQuery 与 Selenium WebDriver 结合使用 - 如何将 JSON 对象转换为 WebElement?

    我正在使用 Selenium WebDriver 我想执行 jQuery 代码来查找一些元素 我的代码如下 public function uploadGrantDoc script return itemlist grant file u
  • 唯一的图像哈希值即使 EXIF 信息更新也不会改变

    我正在寻找一种方法来为 python 和 php 中的图像创建唯一的哈希值 我考虑过对原始文件使用 md5 和 因为它们可以快速生成 但是当我更新 EXIF 信息 有时时区关闭 时 它会更改总和 并且哈希也会更改 有没有其他方法可以为这些文
  • 如何验证上传的文件是视频?

    我的服务器上有一些非常敏感的信息 因此安全性是一个大问题 用户需要能够上传视频 我知道允许用户上传文件会带来安全威胁 因为没有 100 的方法可以阻止他们上传非视频 但我显然可以选择服务器将保留哪些文件 我知道检查文件扩展名是不够的 检查
  • PHP 中正确的存储库模式设计?

    前言 我尝试在具有关系数据库的 MVC 架构中使用存储库模式 我最近开始学习 PHP 中的 TDD 并且我意识到我的数据库与应用程序的其余部分耦合得太紧密 我读过有关存储库并使用国际奥委会容器 http laravel com docs 4
  • 将 Base64 字符串转换为图像文件? [复制]

    这个问题在这里已经有答案了 我正在尝试将我的 Base64 图像字符串转换为图像文件 这是我的 Base64 字符串 http pastebin com ENkTrGNG http pastebin com ENkTrGNG 使用以下代码将
  • 安全地评估简单的数学

    我想知道是否有一种安全的方法来评估数学 例如 2 2 10000 12000 10000 20 2 2 40 20 23 12 无需使用eval 因为输入可以来自任何用户 我需要实现的只是整数的加法和减法 是否有任何已经存在的代码片段 或者
  • 将 Hbase 与 PHP 集成 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我已经安装了 Hbase 现在我正在寻找一些 PHP 库来将 hbase 与 PHP 集成 我尝试了 2 个库 第一个是我尝试与 th
  • SimpleXML 返回空数组

    我正在尝试使用 Google Maps API 和 PHP SimpleXML 获取城市的纬度和经度 我尝试这样做 xml simplexml load file http maps googleapis com maps api geoc
  • jQuery appendTo(), json 在 IE 6,7,8 中不起作用

    我这两天绞尽脑汁想找到解决办法 我使用 jQuery ajax 从数据库中获取值 以便在另一个框发生更改时更新一个框 php 脚本从数据库中获取值 然后输出 json 它在 FF 中工作正常 但在所有版本的 IE 中 选择框都不会更新 我已

随机推荐

  • C# 中的浮动花括号

    今天我遇到了一段以前从未见过的 C 代码 程序员仅使用花括号定义了代码块 没有 if 类 函数等 int i 0 i compile error 除了让代码看起来更有条理之外 这样做还有其他目的吗 使用这种 浮动 上下文是好还是坏 您可以使
  • 如何使用 .gitattributes 避免在 git root 中包含文件夹,但在 zip 的 dist 文件夹中包含同名文件夹

    我有一个名为lib在存储库的根目录和另一个名为lib在 dist 文件夹中 我正在尝试使用 gitattributes文件排除除 dist 之外的所有文件夹和文件 以便任何下载为 zip 或 tarball 的人都只会 git 分发文件 我
  • Android:如何暂停和恢复可运行线程?

    我正在使用 postDelayed 可运行线程 当我按下按钮时 我需要暂停并恢复该线程 请任何人帮助我 这是我的主题 protected void animation music6 music4 postDelayed new Runnab
  • Object.entries() 确实为 Maps 返回一个空数组

    我刚刚发现 那个呼唤Object entries在 Map 上确实返回一个空数组 我希望它返回任何返回的内容Map entries Example let map new Map 1 2 map entries 1 2 Object ent
  • 如何在 Visual C++ 中宣传 Bonjour 服务

    我试图弄清楚这是否可能 但是通过 Visual C 宣传 Bonjour 服务的最简单方法是什么 您可以使用DNS服务发现客户 dns sd Windows Bonjour 安装程序把它放进去C Windows system32 dns s
  • 我可以在 dojo 手风琴中打开特定条目吗?

    我想在应用程序的左侧导航中放置链接 打开 xPage 并选择特定的手风琴条目 不知道该怎么做 有什么想法吗 我在这里假设您想以编程方式执行此操作 看看这个答案 https stackoverflow com a 1190455 104799
  • Laravel 转义 Blade 模板中的所有 HTML

    我正在 Laravel 中构建一个小型 CMS 并尝试显示内容 存储在数据库中 它显示 HTML 标签而不是执行它们 就像所有打印数据都有一个自动 html entity decode 一样
  • Cleancode:在 Promise 中尝试/捕获

    我正在研究 redux form atm 并找到了这段代码 它对我有用 但是有没有更干净的方法可以用 ES6 风格编写它 const asyncValidate values dispatch gt return new Promise r
  • 有效地生成所有排列

    我需要尽快生成所有排列 https en wikipedia org wiki Permutation整数的0 1 2 n 1并得到结果作为NumPy https numpy org 形状数组 factorial n n 或者迭代此类数组的
  • vscode通过SSH连接gitlab的问题

    我在尝试通过 SSH 连接到 GitLab 远程存储库时遇到问题 这里是迄今为止完成的步骤 成功生成 SSH 密钥 管理人员将密钥添加到存储库中 因此当我访问 GitLab 网站时 我可以提交和发布分支 我无法从 VSCODE 发布分支并收
  • iPad Safari 100% 高度问题

    我的页面上有一个模态 div 它使背景变灰 如果我将overlay div的高度设置为100 它在IE 桌面 上工作正常 但在iPad Safari上 完整的高度不会变灰 究竟是什么问题 这与固定位置 视口有关吗 请帮忙 下面是相同的 CS
  • 将 Python 中的 SHA 哈希计算转换为 C#

    有人可以帮我将以下两行 python 代码转换为 C 代码吗 hash hmac new secret data digestmod hashlib sha1 key hash hexdigest 8 如果您有兴趣 其余的看起来像这样 us
  • 需要使用 imap php 保存电子邮件副本,然后可以在 Outlook Express 中打开

    我有 IMAP PHP 脚本 它连接并读取邮箱中的电子邮件 我正在寻找的是 我想将电子邮件保存在服务器磁盘上 并将其命名为 testing eml 文件 因此 当我稍后记下这些电子邮件时 可以在 Outlook Express 中查看 任何
  • 如何在 PHP 中使用 RS256 签署 X.509 证书?无法获取有效指纹...x5t

    我已经实现了 JWT 令牌生成器库Here https github com F21 jwt blob master JWT JWT php 并且我能够获得 RS256 令牌 有效负载 但我对标题数据有疑问 我需要一个标头值 x5t 该标头
  • 在 Magento 中获取购物车详细信息

    我想通过使用 Magento 获取购物车详细信息getQuote功能 我怎样才能做到这一点 cart Mage getModel checkout cart gt getQuote 当我打印 cart页面停止执行并显示空白页面 但是当我写的
  • Azure 网站中的 404 处理

    我在 Azure 上有一个 MVC 网站 我已经编写了一个控制器操作来代表资源 该操作应该返回 HTTP 404 但正文内容应该是一些 HTML 我在其中解释了 404 的原因 这是作为一个标准操作实现的 该操作设置Response Sta
  • 如何在 Safari 上打开本地 html 文件?

    我想打开本地 html 文件Safari集成到我的Swift 3应用 我知道如何使用网址来做到这一点 这是我用来执行此操作的代码 let encodedString url addingPercentEncoding withAllowed
  • Docx 缺少属性

    我正在尝试使用 python 中的 docx 库来考虑 word 文档 问题是 无论我导入什么 我都会收到有关 无属性 的错误消息 例如 文档 from docx import Document 给出输出 cannot import nam
  • 如何使用 solrnet 在 solr 中使字段搜索不区分大小写

    在 solr 模式中我有如下字段
  • 在 php 中将单词转换为数字 II

    这里有一个很棒的功能在 PHP 中将单词转换为数字 https stackoverflow com questions 1077600 converting words to numbers in php来自埃尔约博 但我有一个问题 字符串