如何使用 Python 中的功能和库创建 n-gram的过程

 更新时间:2023年09月28日 14:14:37   作者:迹忆客  
在计算语言学中,n-gram 对于语言处理、上下文和语义分析非常重要,本文将讨论如何使用 Python 中的功能和库创建 n-gram,感兴趣的朋友一起看看吧

在计算语言学中,n-gram 对于语言处理、上下文和语义分析非常重要。它们是从令牌字符串中相邻的连续单词序列。

常见的 n-gram 包括 unigram、bigram 和 trigram,它们是有效的,当 n>3 时可能会遇到数据稀疏的问题。

本文将讨论如何使用 Python 中的功能和库创建 n-gram。

使用 for 循环在 Python 中从文本创建 n-gram

我们可以有效地创建一个 ngrams 函数,该函数接受文本和 n 值,并返回一个包含 n-gram 的列表。

为了创建这个函数,我们可以分割文本并创建一个空列表(output)来存储 n-gram。我们使用 for 循环遍历 splitInput 列表以遍历所有元素。

然后将单词(令牌)添加到 output 列表中。

def ngrams(input, num):
    splitInput = input.split(' ')
    output = []
    for i in range(len(splitInput) - num + 1):
        output.append(splitInput[i:i + num])
    return output
text = "Welcome to the abode, and more importantly, our in-house exceptional cooking service which is close to the Burj Khalifa"
print(ngrams(text, 3))

代码输出:

[['Welcome', 'to', 'the'], ['to', 'the', 'abode,'], ['the', 'abode,', 'and'], ['abode,', 'and', 'more'], ['and', 'more', 'importantly,'], ['more', 'importantly,', 'our'], ['importantly,', 'our', 'in-house'], ['our', 'in-house', 'exceptional'], ['in-house', 'exceptional', 'cooking'], ['exceptional', 'cooking', 'service'], ['cooking', 'service', 'which'], ['service', 'which', 'is'], ['which', 'is', 'close'], ['is', 'close', 'to'], ['close', 'to', 'the'], ['to', 'the', 'Burj'], ['the', 'Burj', 'Khalifa']]

使用 NLTK 在 Python 中创建 n-gram

NLTK 是一个自然语言工具包,提供了一个易于使用的接口,用于文本处理和分词等重要资源。要安装 nltk,我们可以使用以下 pip 命令。

pip install nltk

为了展示潜在问题,让我们使用 word_tokenize() 方法。它可以帮助我们使用 NLTK 推荐的单词分词器创建一个令牌化的文本副本,然后再编写更详细的代码。

import nltk
text = "well the money has finally come"
tokens = nltk.word_tokenize(text)

代码输出:

Traceback (most recent call last):
  File "c:\Users\akinl\Documents\Python\SFTP\n-gram-two.py", line 4, in <module>
    tokens = nltk.word_tokenize(text)
  File "C:\Python310\lib\site-packages\nltk\tokenize\__init__.py", line 129, in word_tokenize
    sentences = [text] if preserve_line else sent_tokenize(text, language)
  File "C:\Python310\lib\site-packages\nltk\tokenize\__init__.py", line 106, in sent_tokenize
    tokenizer = load(f"tokenizers/punkt/{language}.pickle")
  File "C:\Python310\lib\site-packages\nltk\data.py", line 750, in load
    opened_resource = _open(resource_url)
  File "C:\Python310\lib\site-packages\nltk\data.py", line 876, in _open
    return find(path_, path + [""]).open()
  File "C:\Python310\lib\site-packages\nltk\data.py", line 583, in find
    raise LookupError(resource_not_found)
LookupError:
**********************************************************************
  Resource [93mpunkt[0m not found.
  Please use the NLTK Downloader to obtain the resource:

  [31m>>> import nltk
  >>> nltk.download('punkt')
  [0m
  For more information see: https://www.nltk.org/data.html

  Attempted to load [93mtokenizers/punkt/english.pickle[0m

  Searched in:
    - 'C:\\Users\\akinl/nltk_data'
    - 'C:\\Python310\\nltk_data'
    - 'C:\\Python310\\share\\nltk_data'
    - 'C:\\Python310\\lib\\nltk_data'
    - 'C:\\Users\\akinl\\AppData\\Roaming\\nltk_data'
    - 'C:\\nltk_data'
    - 'D:\\nltk_data'
    - 'E:\\nltk_data'
    - ''
**********************************************************************

上述错误消息和问题的原因是 NLTK 库对于某些方法需要某些数据,而我们尚未下载这些数据,特别是如果这是您首次使用的话。因此,我们需要使用 NLTK 下载器来下载两个数据模块,punkt 和 averaged_perceptron_tagger。

当我们使用 words() 等方法时,可以使用这些数据,例如创建一个 Python 文件并运行以下代码以解决该问题。

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

或者通过命令行界面运行以下命令:

python -m nltk.downloader punkt
python -m nltk.downloader averaged_perceptron_tagger

示例代码:

import nltk
text = "well the money has finally come"
tokens = nltk.word_tokenize(text)
textBigGrams = nltk.bigrams(tokens)
textTriGrams = nltk.trigrams(tokens)
print(list(textBigGrams), list(textTriGrams))

代码输出:

[('well', 'the'), ('the', 'money'), ('money', 'has'), ('has', 'finally'), ('finally', 'come')] [('well', 'the', 'money'), ('the', 'money', 'has'), ('money', 'has', 'finally'), ('has', 'finally', 'come')]

示例代码:

import nltk
text = "well the money has finally come"
tokens = nltk.word_tokenize(text)
textBigGrams = nltk.bigrams(tokens)
textTriGrams = nltk.trigrams(tokens)
print("The Bigrams of the Text are")
print(*map(' '.join, textBigGrams), sep=', ')
print("The Trigrams of the Text are")
print(*map(' '.join, textTriGrams), sep=', ')

代码输出:

The Bigrams of the Text are
well the, the money, money has, has finally, finally come

The Trigrams of the Text are
well the money, the money has, money has finally, has finally come

到此这篇关于在 Python 中从文本创建 N-Grams的文章就介绍到这了,更多相关Python 文本创建 N-Grams内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 深入理解Python 多线程

    深入理解Python 多线程

    这篇文章主要介绍了Python 多线程的相关知识,文中讲解的非常详细,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-06-06
  • 解析PyCharm集成GitLab代码仓的问题

    解析PyCharm集成GitLab代码仓的问题

    这篇文章主要介绍了PyCharm集成GitLab代码仓的相关知识,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-09-09
  • Pycharm如何运行.py文件的方法步骤

    Pycharm如何运行.py文件的方法步骤

    这篇文章主要介绍了Pycharm如何运行.py文件的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • Android基于TCP和URL协议的网络编程示例【附demo源码下载】

    Android基于TCP和URL协议的网络编程示例【附demo源码下载】

    这篇文章主要介绍了Android基于TCP和URL协议的网络编程,结合实例形式分析了Android网络编程的通信原理、实现步骤与相关操作技巧,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2018-01-01
  • Python实现基本数据结构中栈的操作示例

    Python实现基本数据结构中栈的操作示例

    这篇文章主要介绍了Python实现基本数据结构中栈的操作,包括基于Python实现栈的定义、入栈、出栈、判断栈空或栈满等情况,需要的朋友可以参考下
    2017-12-12
  • Pytorch损失函数torch.nn.NLLLoss()的使用

    Pytorch损失函数torch.nn.NLLLoss()的使用

    这篇文章主要介绍了Pytorch损失函数torch.nn.NLLLoss()的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • 详解Python开发中如何使用Hook技巧

    详解Python开发中如何使用Hook技巧

    这篇文章主要介绍了详解Python开发中如何使用Hook技巧,详细的介绍了Python Hook的用法和示例,有兴趣的可以了解一下
    2017-11-11
  • Python中ROS和OpenCV结合处理图像问题

    Python中ROS和OpenCV结合处理图像问题

    ROS通过一个叫CvBridge的功能包,将获取的图像数据转换成OpenCV的格式,OpenCV处理之后,传回给ROS进行图像显示(应用),这篇文章主要介绍了Python中ROS和OpenCV结合处理图像问题,需要的朋友可以参考下
    2022-06-06
  • Python入门指南之print()函数的N种高级用法

    Python入门指南之print()函数的N种高级用法

    这篇文章深入讲解了Python中print()函数的高级用法,重点解析了其函数签名和参数配置,文章通过丰富的代码示例展示了print()函数的强大功能,帮助开发者突破简单打印的局限,掌握更专业的输出控制
    2026-06-06
  • Python自动提取邮件订阅链接并解析

    Python自动提取邮件订阅链接并解析

    本文介绍了一个可配置的邮件处理流水线系统,通过多模块协作自动从订阅邮件中提取文章链接并生成AI分析报告,包含配置加载、邮件抓取、URL解析、AI分析和报告生成等核心模块,需要的朋友可以参考下
    2026-05-05

最新评论