【问题标题】:event entities in telethonTelethon 中的事件实体
【发布时间】:2020-11-09 17:27:45
【问题描述】:

当表情符号在文本中时,我遇到了实体问题。

这是我的文字:

❓????????????????️????❓????????????????
abcdefghijklmnop
@aaabbbbbcccc

这是我的实体事件:

entities=[ MessageEntityMention( length=13, offset=49 ), ]

还有我的代码:

txt = event.raw_text
print(event.message.message)
if event.message.entities != None:
   i=0
   c = len(event.message.entities)
   while i<c:
       a = event.message.entities[i]
       if (type(a) is MessageEntityMention) == True:
          print(a)
          o = a.offset
          l = a.length
          eo = o + l
          txt = txt.replace(event.raw_text[o:eo],"@example")
       i=i+1
   print(txt)

这应该将 ID(@aaabbbbbcccc) 更改为 @example,但它没有,并返回:

❓????????????????️????❓????????????????
abcdefghijklmnop
@aaabbbbb@example

问题在于表情符号。当我删除表情符号时它工作正常。

我该怎么办?

【问题讨论】:

    标签: python entities telethon


    【解决方案1】:
    async def handler(event): 
        content = event.raw_text
        for ent, txt in event.get_entities_text():
            # ent : shows you the MessageEntity constructor
            # txt : shows you the text interested
            if isinstance(ent, types.MessageEntityMention): # check if it's a mention
                content = content.replace(txt, '@example')
    

    查看telethon docs 了解有关get_entities_text 的更多信息。

    【讨论】:

      【解决方案2】:

      偏移量是在文本中使用代理计算的,因此您需要在使用helpers.add_surrogate 进行操作之前添加它们:

      from telethon import helpers
      
      text = helpers.add_surrogate(message.raw_text)
      
      ... # work with `text` and `message.entities` (offsets will be OK now)
      
      text = helpers.del_surrogate(text)  # remove the surrogate pairs when done
      

      TheKill 在他们的回答中展示的方法更适合您的具体情况,但如果您需要,这就是它的工作原理。

      【讨论】:

        猜你喜欢
        • 2017-11-10
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-31
        • 2022-12-12
        • 1970-01-01
        相关资源
        最近更新 更多