【发布时间】:2015-09-15 13:18:53
【问题描述】:
我有一个电子表格,在列 (C1:C3159) 中填充了杂乱无章的打开文本字段,我想按文本中的各种关键字对其进行排序。我正在尝试编写一些 python 代码来循环遍历该列,查找关键字,然后根据在文本中找到的单词将该单元格中的字符串类别附加到一个空列表中。到目前为止,我的代码如下所示。
## make an object attr for the column
attr = ['C1:C3159']
## make all lower case
[x.lower() for x in attr]
## initialize an empty list
categories = []
## loop through attr object and append categories to the "categories" list
for i in attr:
if 'pest' or 'weed' or 'disease' or 'cide' or 'incid' or 'trap'/
or 'virus' or 'IPM' or 'blight' or 'incid' or 'rot' or 'suck' in i:
categories.append("pest management")
elif 'fert' or 'dap' or 'urea' or 'manga' or 'npk' pr 'inm' in i:
categories.append("fertilizer")
elif 'wind' or 'rain' or 'irr' or 'alt' or 'moist' or 'soil' or 'ph'\
or 'drip'or 'environ' or 'ec' in i:
categories.append("environment")
elif 'spac' or 'name' or 'stor' or 'yield' or 'rogu' or 'maint'\
or 'cond' or 'prod' or 'fenc' or 'child' or 'row' or 'prun' or 'hoe'\
or 'weight' or 'prep' or 'plot' or 'pull' or 'topp' in i:
categories.append("operations")
elif 'plant' or 'germin' or 'age' or 'bulk' or 'buds' or 'matur'\
or 'harvest' or 'surviv' or 'health' or 'height' or 'grow' in i:
categories.append("life cycle")
elif 'price' or 'sold' or 'inr' or 'cost' in i:
categories.append("market")
elif 'shed' or 'post' or 'fenc' or 'pond' or 'stor' in i:
categories.append("PPE")
else:
categories.append("uncategorized")
我遇到的问题是,在第一个 if 语句之后,elif 语句没有在循环中进行评估,并且我返回的列表仅包含归类为“害虫管理”的少数内容。有谁知道如何做我在这里尝试做的事情,以便评估整个循环?下面发布了列表中字符串的一小部分示例。
attr = ['Age of plantation',
'Altitude of Plantation',
'Annual production Last year (In Kg)',
'Average Price paid per kg in NPR (Last Year)',
'Majority Bush type',
'Pruning Cycle',
'Tea sold to ( Last Year)',
'Boll weight in grams',
'CLCuV incidence %',
'Dibbles per row',
'Gap Filling',
'Germination %',
'Hoeing',
'Land preparation',
'Land preparation date',
'Pest & disease incidence',
'Plot size in metre Square',
'Rows per entry',
'Spacing between plants in cms']
【问题讨论】:
-
感谢您的编辑。在 stackoverflow 中为新手格式化是一个需要克服的不必要的棘手障碍。我现在有足够的代表发布相关数据的图片,这是一个加分项!
标签: python string if-statement for-loop substring