0

所以我正在尝试将口语字母数字字符串转换为可用变量。示例是口语 IP 地址。举个例子:

string(one nine two period one six eight period zero period one slash twenty four) 

把它变成

192.168.000.001/24

我了解一些字符串格式,但这超出了我的知识范围。我想我可以把它变成一本字典。使用变量并将字母数字与数值进行比较。我试图在没有谷歌服务的情况下做到这一点,因为它有电话号码和地址,但不是像 IP 地址这样的东西。

任何帮助表示赞赏。

4

2 回答 2

0

我不相信这个答案。全部学分归于递归 谁在此线程中提供了这个美丽的答案

def text2int(textnum, numwords={}):
if not numwords:
  units = [
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen",
  ]

  tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

  scales = ["hundred", "thousand", "million", "billion", "trillion"]

  numwords["and"] = (1, 0)
  for idx, word in enumerate(units):    numwords[word] = (1, idx)
  for idx, word in enumerate(tens):     numwords[word] = (1, idx * 10)
  for idx, word in enumerate(scales):   numwords[word] = (10 ** (idx * 3 or 2), 0)

current = result = 0
for word in textnum.split():
    if word not in numwords:
      raise Exception("Illegal word: " + word)

    scale, increment = numwords[word]
    current = current * scale + increment
    if scale > 100:
        result += current
        current = 0

return result + current

 print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")
 #7100031337
于 2020-12-03T04:46:59.193 回答
0

如果我正确理解了这个问题,您需要将一串拼写字符(由空格划定)转换为字符本身的字符串。如果是这样,我认为这应该可以解决问题:

def convert_spelled_chars(string:str, mapping:dict):
    # split at whitespace
    tokens = string.split()
    # map to values
    chars = [str(mapping[t]) for t in tokens]
    # join into one string again
    result = "".join(chars)
    return result

这接受字符串,并返回 IP 地址的字符串形式(我假设您希望它作为字符串?)。然后可以通过以下方式使用它:

mapping = {
    "one": 1,
    "two": 2,
    "slash": "/"
}

print(convert_spelled_chars("one two slash two one", mapping))
#> "12/21"

它假设您知道所有可能出现的口语字符,如果您仅将其用于 IP 地址,这似乎是一个合理的假设。

于 2020-12-03T04:41:49.233 回答