python-3.x - 是否有任何用于将文本转换为单词的 python 库?
问题描述
我有一个数据框,其列名称为描述。请查看示例说明
这是我的样本观察:
说明上有编号。我需要将数字转换为文本并需要输出如下
从上面,我想将数字转换为我的 NLP 过程的单词。有没有将数字转换为单词的库?我有 50000 个观察值
请指教。
解决方案
我将在这个答案的开头说,我认为 Pandas 本身肯定有一个更稳定的内置解决方案。
话虽如此,这是使用该num2words
软件包的解决方案:
import num2words
import random
import re
import pandas as pd
def randomSentence(wordList):
"""Uses wordList to create a sentance with random-numbers strewn in."""
words = [random.choice(wordList) for i in range(3)]
for i in range(random.randint(1,4)):
words.append(round(random.uniform(0, 10), 2))
random.shuffle(words)
return " ".join(str(i) for i in words)
def transInt(string):
"""checks if there is a '.' in the given number, and returns the translation."""
if "." in string:
return num2words.num2words(float(string))
return num2words.num2words(int(string))
def replaceInt(string):
"""Replaces integers and floats with a translated string using the function transInt """
return re.sub(r"(\d+\.*\d*)", lambda x: transInt(x.group()), string)
# Lorem ipsum that is used as a wordlist to create sentences.
x = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nam sit amet nunc sollicitudin, viverra dolor ut, feugiat tellus.
Curabitur erat arcu, viverra vitae augue sed, maximus vestibulum ante."""
x = [i.strip(",.") for i in x.split()]
# Creating a list of random sentences, with numbers strewn in
sentences = [randomSentence(x) for i in range(2)]
# Creating a df with each of the sentences.
df = pd.DataFrame(sentences, columns=["Sentence"])
# Adds a new column 'Translated' to the dataframe with the numbers translated.
df["Translated"] = df.Sentence.apply(replaceInt)
for i in df.iterrows():
_, data = i
print(f'Original: {data.Sentence}')
print(f'Translated: {data.Translated}')
print("-"*20)
因为您没有提供简单的复制/粘贴版本DataFrame
,所以我创建了一个函数来返回一个随机句子以供使用。
样本输出:
Original: arcu 7.48 ut 1.53 8.72 sit 7.13
Translated: arcu seven point four eight ut one point five three eight point seven two sit seven point one three
--------------------
Original: elit 3.55 amet 7.88 tellus
Translated: elit three point five five amet seven point eight eight tellus
--------------------
推荐阅读
- java - 如何在数据库中插入一行?
- pipenv - 为什么 pipenv 在名称末尾添加扩展名?
- javascript - 在页面直接到另一个页面后将类添加到 div
- javascript - 以分层/树格式打印 JSON 对象
- javascript - React 服务器组件在 SEO 上的性能
- javascript - 登录后单击硬件后退按钮导航到登录页面如何在离子4中防止它
- python - Python中矩阵铅笔的主要广义特征向量
- sql - 在视图中将字符串转换为日期
- macos - dyld:库未加载:@rpath/libnetcdf.13.dylib ...原因:找不到图像:MacOS Big Sur 上的 GMT
- angular - 使用 Angular 10 时的 CSP 阻止样式和脚本