我有一个数据.txt和一个计数.py. 你知道吗
我的数据在数据.txt看起来像这样:
hermione [
{
keyword.adsf
keyword.bsdf
},
{
keyword.1sdf
keyword.bsd
keyword.bsd
}
]
ron [
{
keyword.adsf
keyword.bsdf
},
{
keyword.1sdf
keyword.bsd
keyword.bsd
}
]
我想做的是使用python计算每个{}中keyword.xxx
出现的次数。换句话说,我希望我的输出是这样的:
hermione [
{
2
},
{
3
}
]
ron [
{
2
},
{
3
}
]
我是这么想的计数.py,我会写脚本来计算,然后数据.txt就像一根大绳子。你知道吗
到目前为止,这是我写的代码:
from sys import argv
script, filename = argv
txt = open(filename).read()
def count_in_bracket():
print txt
print count_in_bracket()
(我在终端中运行pythoncustom_fields_nocount.py custom_fields_nocount.txt
。)
。。。这并不多,因为它不会遍历每个{}括号。你知道吗
这就是我难以理解的部分。我怎么写这样的东西
list = ['ron', 'hermione']
for {} in list:
print len(CONTENTS_OF_EACH_{}.split("keyword"))-1
什么?你知道吗
下面是一种使用纯Python的方法。如果您需要更复杂的处理而不是仅仅计算事物,这可能很方便。你知道吗
使用正则表达式,可以执行以下操作:
这将为您提供一个包含
{}
之间每个字符串的列表工作原理:它先搜索一个开放卷曲,然后搜索一个或多个非封闭卷曲的字符序列,然后搜索封闭卷曲,但只返回括号内的内容。你知道吗
re.DOTALL
将换行符视为常规字符,匹配跨多行的卷曲对。你知道吗相关问题 更多 >
编程相关推荐