如何在 NLTK 中使用 word_tokenize 忽略单词之间的标点符号?

2024-06-24

我希望使用 NLTK word_tokenize 忽略单词之间的字符。

如果我有一句话:

test = 'Should I trade on the S&P? This works with a phone number 333-445-6635 and email [email protected] /cdn-cgi/l/email-protection'

word_tokenize 方法将 S&P 拆分为

'S','&','P','?'

有没有办法让这个库忽略单词或字母之间的标点符号? 预期输出:'S&P','?'


让我知道这对你的句子有何作用。
我添加了一个带有一堆标点符号的附加测试。
最后部分的正则表达式是根据 WordPunctTokenizer 正则表达式修改的。

from nltk.tokenize import RegexpTokenizer

punctuation = r'[]!"$%&\'()*+,./:;=#@?[\\^_`{|}~-]?'
tokenizer = RegexpTokenizer(r'\w+' + punctuation + r'\w+?|[^\s]+?')

# result: 
In [156]: tokenizer.tokenize(test)
Out[156]: ['Should', 'I', 'trade', 'on', 'the', 'S&P', '?']

# additional test:
In [225]: tokenizer.tokenize('"I am tired," she said.')
Out[225]: ['"', 'I', 'am', 'tired', ',', '"', 'she', 'said', '.']

编辑:要求发生了一些变化,因此我们可以稍微修改波茨 TweetTokenizer https://github.com/adonoho/TweetTokenizers/blob/master/PottsTweetTokenizer.py以此目的。

emoticon_string = r"""
    (?:
      [<>]?
      [:;=8]                     # eyes
      [\-o\*\']?                 # optional nose
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth      
      |
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
      [\-o\*\']?                 # optional nose
      [:;=8]                     # eyes
      [<>]?
    )"""
# Twitter symbols/cashtags:  # Added by awd, 20140410.
# Based upon Twitter's regex described here: <https://blog.twitter.com/2013/symbols-entities-tweets>.
cashtag_string = r"""(?:\$[a-zA-Z]{1,6}([._][a-zA-Z]{1,2})?)"""

# The components of the tokenizer:
regex_strings = (
    # Phone numbers:
    r"""
    (?:
      (?:            # (international)
        \+?[01]
        [\-\s.]*
      )?            
      (?:            # (area code)
        [\(]?
        \d{3}
        [\-\s.\)]*
      )?    
      \d{3}          # exchange
      [\-\s.]*   
      \d{4}          # base
    )"""
    ,
    # Emoticons:
    emoticon_string
    ,
    # HTML tags:
    r"""(?:<[^>]+>)"""
    ,
    # URLs:
    r"""(?:http[s]?://t.co/[a-zA-Z0-9]+)"""
    ,
    # Twitter username:
    r"""(?:@[\w_]+)"""
    ,
    # Twitter hashtags:
    r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)"""
    ,
    # Twitter symbols/cashtags:
    cashtag_string
    ,
    # email addresses
    r"""(?:[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-])""",
    # Remaining word types:
    r"""
    (?:[a-z][^\s]+[a-z])           # Words with punctuation (modification here).
    |
    (?:[+\-]?\d+[,/.:-]\d+[+\-]?)  # Numbers, including fractions, decimals.
    |
    (?:[\w_]+)                     # Words without apostrophes or dashes.
    |
    (?:\.(?:\s*\.){1,})            # Ellipsis dots. 
    |
    (?:\S)                         # Everything else that isn't whitespace.
    """
    )
word_re = re.compile(r"""(%s)""" % "|".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)
# The emoticon and cashtag strings get their own regex so that we can preserve case for them as needed:
emoticon_re = re.compile(emoticon_string, re.VERBOSE | re.I | re.UNICODE)
cashtag_re = re.compile(cashtag_string, re.VERBOSE | re.I | re.UNICODE)

# These are for regularizing HTML entities to Unicode:
html_entity_digit_re = re.compile(r"&#\d+;")
html_entity_alpha_re = re.compile(r"&\w+;")
amp = "&amp;"

class CustomTweetTokenizer(object):
    def __init__(self, *, preserve_case: bool=False):
        self.preserve_case = preserve_case

    def tokenize(self, tweet: str) -> list:
        """
        Argument: tweet -- any string object.
        Value: a tokenized list of strings; concatenating this list returns the original string if preserve_case=True
        """
        # Fix HTML character entitites:
        tweet = self._html2unicode(tweet)
        # Tokenize:
        matches = word_re.finditer(tweet)
        if self.preserve_case:
            return [match.group() for match in matches]
        return [self._normalize_token(match.group()) for match in matches]

    @staticmethod
    def _normalize_token(token: str) -> str:

        if emoticon_re.search(token):
            # Avoid changing emoticons like :D into :d
            return token
        if token.startswith('$') and cashtag_re.search(token):
            return token.upper()
        return token.lower()

    @staticmethod
    def _html2unicode(tweet: str) -> str:
        """
        Internal method that seeks to replace all the HTML entities in
        tweet with their corresponding unicode characters.
        """
        # First the digits:
        ents = set(html_entity_digit_re.findall(tweet))
        if len(ents) > 0:
            for ent in ents:
                entnum = ent[2:-1]
                try:
                    entnum = int(entnum)
                    tweet = tweet.replace(ent, chr(entnum))
                except:
                    pass
        # Now the alpha versions:
        ents = set(html_entity_alpha_re.findall(tweet))
        ents = filter((lambda x: x != amp), ents)
        for ent in ents:
            entname = ent[1:-1]
            try:
                tweet = tweet.replace(ent, chr(html.entities.name2codepoint[entname]))
            except:
                pass
            tweet = tweet.replace(amp, " and ")
        return tweet

测试一下:

tknzr = CustomTweetTokenizer(preserve_case=True)
tknzr.tokenize(test)

# result:
['Should',
 'I',
 'trade',
 'on',
 'the',
 'S&P',
 '?',
 'This',
 'works',
 'with',
 'a',
 'phone',
 'number',
 '333-445-6635',
 'and',
 'email',
 '[email protected] /cdn-cgi/l/email-protection']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 NLTK 中使用 word_tokenize 忽略单词之间的标点符号? 的相关文章

随机推荐

  • AND OR 导致显示的结果多于应有的结果

    我正在尝试显示特定时间范围内匹配的结果 效果很好 但是 我想添加一个子句 表示显示的结果必须是 party type1 or 2 所以我这样做了 WHERE start datetime gt DATE START SELECTED AND
  • iOS 10.核心数据插入新对象 sigABRT

    我尝试了 forEntityName Game MyApp Game 在我的 dataManagerFile 中 let appDelegate UIApplication shared delegate as AppDelegate le
  • 如何将微调器添加为导航抽屉中的项目

    I want to add spinner as an item in my navigation drawer Where should I put the spinner as an item Where to inflate the
  • Servlet @WebServlet urlPatterns

    这是一个简单的问题 但我找不到快速的答案 现在我有一个servlet BaseServlet 当用户请求以下任何网址时 host host host BaseServlet 它应该始终引用相同的 servlet 并重定向到主页 当我设定 W
  • 将多个侦听器绑定到同一端口

    我在用UdpClient上课于 net 3 5我需要将多个应用程序绑定到同一个端口 So if UDP服务器广播任何请求 所有侦听该端口的应用程序都可以接收该消息 但问题是 当我尝试将应用程序绑定到同一端口时 只有一个应用程序接收该消息 而
  • 实体框架中是否存在 NHibernate.ToFuture() 扩展方法的类似方法?

    所以问题就在标题中 NHibernate 用户可以做什么 var q1 Source Companies ToFuture var q2 Source Items ToFuture var q3 Source Users ToFuture
  • 如何判断表格行是否可见?

    我想知道如何识别表行是否可见 我想使用 jQuery 来解决 您可以使用 visible http api jquery com visible selector 伪选择器 以及is http api jquery com is 方法 返回
  • Angularjs - $http 成功与当时

    我想问一下这个方法有什么区别 我关心的是 then 和 success function 和 error 之间的区别 谢谢 Simple GET request example http method GET url someUrl the
  • ggplot geom_text字体大小控制

    我尝试将条形图标签的字体更改为 10ggplot2通过这样做 ggplot data file aes x V1 y V3 fill V2 geom bar stat identity position dodge colour white
  • type: 定义一个只能是某些字符串的类型?

    我怎样才能使用typing模块 创建一个可以是某些字符串的类型 例如 假设我需要一个类型CondOperator 可以是以下任何字符串 gt lt gt lt lt gt 我本来希望CondOperator String gt lt gt
  • 发生了类型为“System.AccessViolationException”的未处理异常

    我有以下课程 public class RecipeItem public Guid ID get set public string Title get set public string Instructions get set pub
  • 将 SQL 转储导入 PostgreSQL 数据库

    我们正在切换主机 旧主机提供了我们站点 PostgreSQL 数据库的 SQL 转储 现在 我尝试在本地 WAMP 服务器上进行设置来测试这一点 唯一的问题是我不知道如何在我设置的 PostgreSQL 9 中导入这个数据库 我尝试了 pg
  • Python fuzzywuzzy 错误字符串或缓冲区期望

    我正在使用 fuzzywuzzy 在公司名称 csv 中查找近似匹配项 我正在将手动匹配的字符串与不匹配的字符串进行比较 希望找到一些有用的邻近匹配 但是 我在 fuzzywuzzy 中遇到了字符串或缓冲区错误 我的代码是 from fuz
  • typescript 派生类不能有相同的变量名?

    为什么 TypeScript 派生类不能具有相同的变量名 即使这些成员也是私人的 有没有替代方案 或者我做错了什么 class ClassTS private nom string ClaseTS constructor class Cla
  • 获取 foreach json 架构错误的属性

    我正在尝试确定哪个属性导致了错误 似乎对于每种类型的错误 获取属性的方式都是不同的 from jsonschema import Draft4Validator request json num pages invalid duration
  • couchdb 查询带有关键参数的视图

    没有关键参数 视图可以正常工作 curl http 127 0 0 1 5984 music design albums view by release date total rows 311 offset 0 rows id a4327d
  • 跨浏览器AJAX功能动态加载HTML

    我正在寻找一个 AJAX 函数来动态请求 HTML 页面 我已经找到以下内容 function ajaxinclude url var page request false if window XMLHttpRequest if Mozil
  • Cordova - 检查 WIFI 连接到互联网

    我使用 Cordova 开发智能手机应用程序 在此应用程序中 我需要在向服务器发送请求之前检查互联网连接 为了做到这一点 我使用了 Cordova Connection API 但在设备连接到没有互联网连接的 WIFI 网络的情况下 该 A
  • 此时无法启动异步操作调用WebService出现异常?

    在我的 ASP NET MVC 3 项目中 我调用 Web 服务进行登录身份验证 但它抛出一个异常 异常详细信息 此时无法启动异步操作 异步操作只能在异步处理程序或模块内启动 或者在页面生命周期中的某些事件期间启动 如果在执行页面时发生此异
  • 如何在 NLTK 中使用 word_tokenize 忽略单词之间的标点符号?

    我希望使用 NLTK word tokenize 忽略单词之间的字符 如果我有一句话 test Should I trade on the S P This works with a phone number 333 445 6635 an