使用 tweepy 测试字段是否为 NONE

Testing if field is NONE with tweepy

我正在尝试通过 tweepy 学习 Python。简单的机器人非常简单。

我创建了一个搜索词,但我想知道推文来自哪个城市。

作为测试,我有这段代码:

if ' trump ' in status.text.lower():
    print status.coordinates 
    print ('geo'), status.geo
    print status.text

但是我看到坐标和地理都是None

我如何测试该值是否为 none,并避免看到这些结果?

我可以建议你两种可能的方式:

  1. 您可以在 if 语句中添加一个条件,如下所示:

    if 'trump' in status.text.lower() and status.coordinates is not None:
    

    None 不是字符串,所以这是因为您的代码 (if status.coordinates != "None") 引发了 SyntaxError。

  2. 不要在 if 条件中更改或添加任何内容,仅当它不是 None 时才打印值。
    一种可能的方法如下:

    if status.coordinates is not None:
        print status.coordinates
    

    if status.coordinates:
        print status.coordinates
    

    和完整的脚本:

    if 'trump' in status.text.lower():
        if status.coordinates is not None:
            print status.coordinates
        if status.geo is not None:
            print ('geo'), status.geo
        print status.text