首页 > 解决方案 > 在模块中转换 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

标签: pythonmodule

解决方案


如果使用 import 导入mymodule,则必须指定mymodule.data_clean(). 此外,您不应将代码留在模块中的函数之外。将所有内容放入您的data_clean函数中似乎是一种更清洁的方式


推荐阅读