在PHP中将单词转换为数字 [英] Converting words to numbers in PHP

查看:103
本文介绍了在PHP中将单词转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以单词形式写入的数值转换为整数.例如, "iPhone有23.873万个应用程序" 会成为 "iPhone作为230783个应用"

I am trying to convert numerical values written as words into integers. For example, "iPhone has two hundred and thirty thousand seven hundred and eighty three apps" would become "iPhone as 230783 apps"

在我开始编码之前,我想知道此转换是否存在任何功能/代码.

Before i start coding, I would like to know if any function / code exists for this conversion.

推荐答案

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

There are lots of pages discussing the conversion from numbers to words. Not so many for the reverse direction. The best I could find was some pseudo-code on Ask Yahoo. See http://answers.yahoo.com/question/index?qid=20090216103754AAONnDz for a nice algorithm:

嗯,总的来说,您正在做两件事:查找标记(转换为数字的单词)和应用语法.简而言之,您正在为一种非常有限的语言构建解析器.

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.

您需要的令牌是:

电源:千,百万,十亿
一百:一百
十:二十,三十...九十
单位:一,二,三,...九,
特别:十,十一,十二,...十九

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

(删除任何和",因为它们没有意义.将连字符分成两个记号.即应将"65"处理为"60"五个")

(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. 从右侧获取所有令牌,直到您按下POWER或整个字符串为止.

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

在这些模式的停止点之后解析令牌:

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.

如果您停在整个字符串上,就算完成了.

If you stopped at the whole string you are done.

如果您停电了,请从第1步重新开始,直到达到更高的POWER或整个弦为止.

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

这篇关于在PHP中将单词转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆