A stockpile of functions used to analyze / aggregate the logs of each server and program. If you want to analyze logs with Python, please refer to it!
Use split. The usage of split is roughly divided.
--Do not specify a delimiter like `str.split ()`
--``` str.split ('delimiter') Specify a delimiter like `` `, and have the string str returned a list separated by the specified delimiter.
There are two uses for this.
Use the former `str.split ()`
.
Logs are often separated by tabs or a single character of space.
It is good to specify the delimiter if the delimiter is unified in the log, but unfortunately, both the tab and the space for one character may be confused.
str.split()If so, the tab and the space for one character will be separated as the same "space".
Of course, when separated by commas, etc., use `` `str.split ('separator')` ``.
# Count
When counting the number of accesses
#### **` count.py`**
```py
#Function to count
def count( targets):
cnt = {}
for target in targets:
if target in cnt.keys():
cnt[target] += 1
else:
cnt[target] = 1
return cnt
#I want to find out the number of occurrences of a character string in this list...
targets = ['aaa','bbb','ccc','aaa','bbb','aaa']
#Call the function to count
result = count( targets)
#Viewing count results
for key in result.keys():
print(key + ':' + result[key])
You can implement such a function and call it, but the `` `collections.Counter``` class that counts just by creating an instance in the Collections included in the standard Python3 package. There is, so let's use it.
If you rewrite the count.py written above using the `` `collections.Counter``` class, it will look like this.
count.py
import collections
#I want to find out the number of occurrences of a character string in this list...
targets = ['aaa','bbb','ccc','aaa','bbb','aaa']
#Call the function to count
result = collections.Counter( targets)
#Viewing count results
for key in result.keys():
print(key + ':' + result[key])
The method of viewing the count results does not change. If so, it's better to use the `` `collections.Counter``` class, which can do other things as well as count!
Recommended Posts