【问题标题】:loops & string processing error due to logical flaw - python由于逻辑缺陷导致的循环和字符串处理错误 - python
【发布时间】:2014-11-19 07:54:08
【问题描述】:

我有一个标签列表,并试图打破一些包含多个单词的标签。

data = ['Open Source','Software Development','JavaScript','Technology','Web Development''Programming','Mobile Development','Technology','Professionals''Software''HTML5' ],[..]....]

我用于清理数据并保留一些唯一标签的代码 -

def break_tags(data):

big_tags = []
for n in range(len(data)):

    tags = []

    for item in data[n][5:23]:
        if item != nan:
            if 'open source' in str(item).lower():
                tags.append('open source')
            if 'data science' in str(item).lower():
                tags.append('data science')

            else:
                item = str(item).lower().split(' ')
                tags.extend([e.strip("'():,&;+?][ ") for e in item if e not in remove])
    big_tags.append(tags)
return big_tags

运行 break_tags(data) 后的结果

original_list1 - ['Open Source' '软件开发' 'JavaScript' '技术','Web 开发' '编程','移动开发','技术','Professionals' '软件''HTML5']

new_list1 - ['开源','开放','源','软件','开发', “javascript”、“技术”、“网络”、“开发”、“编程”、 “移动”、“开发”、“技术”、“专业人员”、“软件”、 'html5']

原始列表2:['数据管理','云计算','大数据','数据分析', “数据可视化”、“预测分析”、“NoSQL”、 “数据科学”、“数据分析与建模”、 '统计和数据分析']

new_list2:['数据','管理','云','计算','大数据','大', “数据”、“数据”、“分析”、“数据”、“可视化”、“预测”、 '分析','nosql','数据科学','数据','科学','数据', “分析”、“建模”、“统计”、“数据”、“分析”]


我编写了函数来保留'开源'和'数据科学',并将所有其他标签分解为单个单词。但显然存在一些逻辑缺陷,不仅保持这两个标签完整,而且打破这两个标签分隔单词(见上面的粗体字)

有人可以帮助确定这里的问题吗?谢谢!

【问题讨论】:

    标签: string python-2.7 loops if-statement


    【解决方案1】:

    您的问题在于您的 if/if/else 条件:

    if 'open source' in str(item).lower():
        tags.append('open source')
    if 'data science' in str(item).lower():
        tags.append('data science')
    else:
        item = str(item).lower().split(' ')
        tags.extend([e.strip("'():,&;+?][ ") for e in item if e not in remove]
    

    假设项目是“开源”,那么您将通过第一个 if 并附加“开源”。然后你将测试 VS 'data science' 并通过 else bloc。

    您将不得不使用以下内容进行测试:

    if ('data science' in str(item).lower()) or ('open source' in str(item).lower()):
        if ('data science' in str(item).lower()):
            tags.append('data science')
        else:
            tags.append('open source')
    else:
        item = str(item).lower().split(' ')
        tags.extend([e.strip("'():,&;+?][ ") for e in item if e not in remove]
    

    或者,假设 str(item).lower() 完全是“数据科学”或“开源”:

    if str(item).lower() in ['data science', 'open source']:
        tags.append(str(item).lower())
    else:
        item = str(item).lower().split(' ')
        tags.extend([e.strip("'():,&;+?][ ") for e in item if e not in remove]
    

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多