python - 如何不反转十进制数?

标签 python regex

首先,你不需要懂阿拉伯语来回答这个问题,只需要知道阿拉伯语是从右到左书写的,而阿拉伯语中的数字本身也是从左到右书写的。

我正在尝试将英语项目翻译成阿拉伯语并打印出来。 例如: “paper roll 2.50m x 3.36m VIP”翻译成阿拉伯语是“VIP لف ورو 2.50 م × 3.36 م”

我用正则表达式看有没有未覆盖的单词(英文单词和数字)不去反转

english = re.compile("^[A-Za-z0-9_.]+$")
item_name = "paper roll 2.50m x 3.36m VIP"

''.join(s if english.match(s) else s[::-1] for s in reversed(re.split('(\w+)', arabic_reshaper.reshape(GoogleTranslator(source='en', target='ar').translate(item_name)))))

这里的问题是正则表达式将单词视为“50”、“.”和“2”代表“2.50”,然后将其变为“50.2”,因此输出变为“VIP لف ورو 50.2 م × 36.3 م”,这是不正确的。

有没有可能我可以检查单词是否为十进制数而不使用正则表达式反转它?

最佳答案

我没有安装谷歌翻译,但你可以试试:

  1. re.findall(r'(\d+\.\d+)|(\w+)', item_name) 而不是 re.split 你正在使用。这将生成一个元组列表,例如 [('', 'paper'), ('', 'roll'), ('2.50', ''), ('', 'm'), (' ', 'x'), ('3.36', ''), ('', 'm'), ('', 'VIP')]

  2. 现在在您的条件表达式中使用该元组列表,例如:

    [t[0] if t[0] else t[1] if english.match(t[1]) else t[1][::-1] for t in reversed(re.findall (r'(\d+\.\d+)|(\w+)', item_name))]


附上您的评论:

  1. 您示例中的 × 与面向 ASCII 的 \w 不匹配; ×是一个扩展的UNICODE代码点。

  2. 您可以尝试 \S,它是任何与 × 匹配的非空白字符。

  3. 使用 ' '.join(...) 重新创建空间。

给定:

raw_output='م 26.3 × م 50.2 قرو ةفل VIP'

尝试:

' '.join([t[0] if t[0] else t[1] if english.match(t[1]) else t[1][::-1] for t in reversed(re.findall(r'(\d+\.\d+)|(\S+)', raw_output))])

结果:

VIP لفة ورق 50.2 م × 26.3 م

关于python - 如何不反转十进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70251689/

相关文章:

regex - 两种模式之间的 Postgres regexp_matches

python - 在父函数中使用子函数覆盖的值

python - 在 Python 中使用&符号修复无效的 XML

python - 如何更改pyplot轴的增量

regex - 如何通过正则表达式分隔的拆分函数将VBA中的字符串拆分为数组

regex - 日志文件的 SED 正则表达式替换

Python - Pandas - 'normal' 列的唯一约束

python - 在python中同时并行化不同的功能

regex - 如何在 visual studio 代码片段上应用 more than on transform?

用于匹配 5 位或 9 位邮政编码的 Javascript 正则表达式