我有一个程序,我正在工作,我需要读取一个。txt文件,其中有多行数据,看起来像这样:
[ABC/DEF//25 ghi////JKLM//675//)
我下面的程序可以在新的行上打印每个序列进行分析,但是函数是我遇到问题的地方。我可以让它删除单个数值& 675&;留下字母数字的。(从样本中删除675)
a = "string.txt"
file1 = open(a, "r")
with open(a, 'r') as file:
lines = [line.rstrip('n') for line in file]
print(*lines, sep = "n")
cleaned_data = []
def split_lines(lines, delimiter, remove = '[0-9]+$'):
for line in lines:
tokens = line.split(delimiter)
tokens = [re.sub(remove, "", token) for token in tokens]
clean_list = list(filter(lambda e:e.strip(), tokens))
cleaned_data.append(clean_list)
print(clean_list) # Quick check if function works
split_lines(lines, "/")
然后像这样打印分隔的行,删除空白(在"/"是,和数值)
["ABC","DEF","25 ghi","JKLM"]
我要做的就是使用"cleaned_data"列表,包含这些新分隔的行,并将它们量化以输出如下内容:
4 x["ABC","DEF","25 ghi","JKLM"]
接下来我可以使用"cleaned_data"做什么?读取每行并打印重复字符串的计数?
from pprint import pprint
unique_data = {}
cleaned_data = [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 3, 4, 5, 'a', 'b', [1, 2,
],
[1, 2, ]]
for item in cleaned_data:
key = str(item) # convert mutable objects like list to immutable string.
if not unique_data.get(key): # key does not exist
unique_data[key] = 1, item # Add count of 1 and the data
else: # A duplicate has been encountered
# Increment the count
unique_data[key] = (unique_data[key][0] + 1), item
for k, v in unique_data.items():
print(f"{v[0]}:{v[1]}")
输出:
1:1
1:2
2:3
2:4
2:5
2:a
2:b
1:c
1:d
2:[1, 2]
如果您只需要删除重复项:
deduped_row_of_cleaned_data = list(set(row_of_cleaned_data))
如果你需要知道有多少个重复,只需从len(row_of_cleaned_data)中减去len(deduped_row_of_cleaned_data)。
如果你需要一个所有重复的计数,你可以从你的删除行创建一个分配空字典的列表:
empty_dict=dict.from_keys(list(set(row_of_cleaned_data)),[])
然后循环遍历列表以添加每个值:
for item in row_of_cleaned_data:
empty_dict[item].append(item)
遍历字典获取计数:
for key, value in empty_dict.items():
empty_dict[key] = len(value)
之后,在
中有已删除的数据list(empty_dict.keys())
和
中每个项目的计数list(empty_dict.values()).