Python字符串处理函数报错:NameError: name 'string' is not defined
问题分析与解决方案
错误原因
你遇到的NameError: name 'string' is not defined是因为代码中string= string.fillna('').map(string_oper)这一行里,右侧的string变量在赋值前并未被定义。而且从需求来看,你要处理的是单个字符串,没必要使用pandas的fillna和map方法——这些是用于处理批量数据(比如Series/DataFrame)的,和你的单字符串处理需求不匹配。
正确实现代码
下面是符合需求的函数实现,同时修正了逻辑错误:
def remove_duplicate_char_words(input_str): # 分割字符串为单词列表 words = input_str.split() # 过滤出无重复字符的单词:集合长度等于单词长度则无重复 filtered_words = [word for word in words if len(set(word)) == len(word)] # 拼接成结果字符串 return ' '.join(filtered_words) # 测试示例 input_example = "This is an example" output_example = remove_duplicate_char_words(input_example) print(output_example) # 输出: This is an
错误代码修正说明
如果你原本是想处理pandas中的字符串列,那应该先定义好对应的Series/DataFrame变量,比如:
import pandas as pd def remove_duplicate_char_words(input_str): words = input_str.split() filtered_words = [word for word in words if len(set(word)) == len(word)] return ' '.join(filtered_words) # 假设你的数据存在df的text列中 df = pd.DataFrame({'text': ["This is an example", "Hello world test"]}) # 正确操作:用df['text']而非未定义的string df['processed_text'] = df['text'].fillna('').map(remove_duplicate_char_words) print(df['processed_text'])
这里的核心是:确保你引用的变量(比如df['text'])是已经定义好的,而不是使用未初始化的string变量。
内容的提问来源于stack exchange,提问作者Priyanka
相关产品推荐
相关产品推荐

