python - 在模块中转换 python 脚本
问题描述
我制作了一个 python 脚本,我想将它转换成一个模块,以使用我在其他任务中对文本所做的所有处理。
我正在尝试将脚本转换为模块:**
我的模块.py
import re
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'Hello ONE /TeSt bar FOO bARR foo Bar'.split(),
'B': 'one one two three two two one three'.split()})
###Function 1####
def lower_text(token):
token = token.lower()
return token
df['A'] = df.A.apply(lambda x: lower_text(x))
###Function 2###
def punct(token):
token = re.sub(r'[^\w\s]',' ', token)
return token
df['A'] = df.A.apply(lambda x: punct(x))
###Replace###
df["A"] = df["A"].replace('foo', 'fuzzy', regex=True)
###Function that must return the final data, with all functions applied###
def data_clean():
return df
if __name__ == '__main__':
data_clean()
我想在其他任务中使用这个脚本产生的数据,所以我想把这个脚本变成一个模块。所以我可以导入它,处理数据。但是我不知道该怎么做...
示例:
import mymodule
###Trying to print the preprocessed data###
data = data_clean()
###tasks like LDA, ngrams, visualization...###
...
错误:
NameError Traceback (most recent call last)
<ipython-input-2-c046afd3b89d> in <module>
----> 1 data = data_clean()
NameError: name 'data_clean' is not defined
解决方案
如果使用 import 导入mymodule
,则必须指定mymodule.data_clean()
. 此外,您不应将代码留在模块中的函数之外。将所有内容放入您的data_clean
函数中似乎是一种更清洁的方式
推荐阅读
- entity-framework - 为什么依赖注入不知道我的仓库?
- xml - 在可视化映射器中将命名空间添加到根节点
- rdf - 几次后,当我将它连接到 fuseki 时,为什么 RDFConnection 会阻塞?
- python - Predix - 与 Flask Python 服务器通信的聚合物前端?
- python - 如何为具有可变范围的 for 循环设置动画
- javascript - 从两个不同的按钮打开菜单
- html - 通过 id vb.net 获取 html 元素
- symfony - Symfony Bundle 需要每个项目不同的文件
- python - python ffmpeg moov atom not found 处理输入时数据无效
- c++ - 随机打开的exe列表