使用pandas DataFrames进行文本处理。
项目描述
tidytext-py
使用pandas DataFrames的便捷文本处理。
此库是R包tidytext的Python端口。
安装
pip install tidytext
这将还会安装nltk包。但是,您需要下载额外的资源才能使用tidytext,请使用以下代码。
nltk.download("punkt")
实现的功能
- bind_tfidf
- unnest_tokens
示例
unnest_tokens
import pandas as pd
pd.set_option("display.max_rows", 6)
zen = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
zen_split = zen.splitlines()
df = pd.DataFrame({
"zen": zen_split,
"line": list(range(len(zen_split)))
})
df
zen | line | |
---|---|---|
0 | 0 | |
1 | Python之禅,由Tim Peters撰写 | 1 |
2 | 2 | |
... | ... | ... |
19 | 如果实现难以解释,则不是一个好主意。 | 19 |
20 | 如果实现易于解释,可能是一个好主意。 | 20 |
21 | 命名空间是一个非常好的想法 -- 让我们多做些这样的工作! | 21 |
22行 × 2列
from tidytext import unnest_tokens
unnest_tokens(df, "word", "zen")
line | word | |
---|---|---|
0 | 0 | NaN |
1 | 1 | the |
1 | 1 | zen |
... | ... | ... |
21 | 21 | more |
21 | 21 | of |
21 | 21 | those |
145行 × 2列
bind_tf_idf
from tidytext import unnest_tokens, bind_tf_idf
from siuba import _, count, arrange
(df
>> unnest_tokens(_.word, _.zen)
>> count(_.line, _.word)
>> bind_tf_idf(_.word, _.line, _.n)
>> arrange(-_.tf_idf)
)
line | word | n | tf | idf | tf_idf | |
---|---|---|---|---|---|---|
37 | 9 | counts | 1 | 0.500000 | 2.995732 | 1.497866 |
38 | 9 | readability | 1 | 0.500000 | 2.995732 | 1.497866 |
56 | 13 | explicitly | 1 | 0.333333 | 2.995732 | 0.998577 |
... | ... | ... | ... | ... | ... | ... |
99 | 18 | is | 1 | 0.125000 | 0.693147 | 0.086643 |
112 | 19 | is | 1 | 0.090909 | 0.693147 | 0.063013 |
124 | 20 | is | 1 | 0.076923 | 0.693147 | 0.053319 |
140行 × 6列
项目详情
关闭
tidytext-0.0.1.tar.gz的哈希
算法 | 哈希摘要 | |
---|---|---|
SHA256 | a17cf0b3878b95552e3017dc55f0c9304347f0253f9d90d71f7803e7dcafe404 |
|
MD5 | 34f6afe28eb9b5e29dac906c4167a2f8 |
|
BLAKE2b-256 | c10c07991d5b50a105d37242d616ebfe4d8e03f5fc13bb5b0c671778a4f2925d |