简体   繁体   English

如何在python中过滤并将unicode转换为整数

[英]How do filter and convert unicode to integer in python

I have a unicode attribute which in the below format. 我有一个unicode属性,格式如下。 It can have a period or no event 它可以有一个时期或没有事件

x = P(1 s) or P(0.1 s) or P(0.01 s) or "No Event"

I need to check if x has a period and filter out only the number if it is period and convert it into an integer and export it to excel. 我需要检查x是否具有句点,如果它是句点,则仅过滤出数字,并将其转换为整数并将其导出到excel。 I know how to export to excel, but unable to filter. 我知道如何导出到excel,但无法过滤。 If I use int(), it will give error if the attribute has not period, since they are only characters. 如果我使用int(),如果属性没有句号,它将给出错误信息,因为它们只是字符。

if x == "No Event":
    # Handle no-event situation
    pass
elif x.startswith("P("):
    # extract the number
    s = x[2:].split()[0]
    if "." in s:
        # period present
        result = float(s)
    else:
        # period not present
        result = int(s)
else:
    # Handle unexpected input
    pass

Knowing the expected input precisely including all possible variations (allowed white space and so on) a shorter solution can be written using regular expression. 准确知道预期的输入(包括所有可能的变化(允许的空格等)),可以使用正则表达式编写一个较短的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM