【问题标题】:Replace List in Json Object Function替换 Json 对象函数中的列表
【发布时间】:2014-02-12 20:19:40
【问题描述】:

我一直在玩

下面是我的代码:

def extract_info(msg):
    created_time = msg['created_time'].replace('T', ' ').replace('+0000', '')
    mess = msg.get('message', 'Key "message" is not present.').replace('\n', '').replace(',', '').encode('utf8') 
    message = (mess[:498] + '..') if len(mess) > 498 else mess
    user_id = msg['from']['id']
    return (created_time, message, user_id)



def main():
    ts = FacebookSearch()
    data = ts.search('dishwasher')
    js = json.loads(data)
    messages = (extract_info(msg) for msg in js.get('data', []))
    write_csv('fb_dishwasher.csv', messages, append=True)

上面代码的问题:

我想通过替换使用忽略列表来操作“消息”。

有点我想做的事:

ignore = ["you","all","has","can","that", "the", "what", "with", "and", "to", "this", "would","from", "your", "which", "while", "these", "when", "way", "like", "been", "will", "look"]

def replaceall(s, olds, replacement):
    for old in olds:
        s = s.replace(old, replacement)
    return s

最大的问题是我不确定如何将上面的忽略列表融入我现有的“extract_info”函数中。我是创建一个新函数还是在现有函数中创建一个嵌套函数。 (感觉不对)。我真的很想就实现这一目标的最佳方式提出一些想法和想法。

【问题讨论】:

  • 您似乎已经有了替换函数,可以在 extract_info 函数中调用它。问题是什么?也许我不清楚这个问题。
  • 你想如何“使用忽略列表操作消息”?消息应该如何改变?这些词应该被删除吗?请举个例子。
  • 忽略列表中的单词应该被删除。例如:“去商店”将是“去商店”

标签: python list function replace


【解决方案1】:

extract_info 似乎每次都收到 single 消息,也许你最好在那里使用 e 函数而不是一次对所有消息执行 relaceall,即:

message = message.replace(old, replacement)

【讨论】:

  • 我认为这可能是最好的方法。谢谢小伙子!!
猜你喜欢
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2018-05-01
相关资源
最近更新 更多