python读取文件

img


文本如上,因为发不了文件,所以大致说一下,里面有男性女性名字,并且都有带胜字和不带的,要求就是要分别写出男女中带胜字名字出现的频率,我自己写了好多遍还是会对女性抛出除数为0的错误,实在是搞不懂到底是读取没成功还是咋了,文件位置如下

img

img

你自己看一下吧,随便写的,不一定对

with open('names.txt', 'r', encoding='utf-8') as f:
    names = f.readlines()
male_with_sheng = 0
male_without_sheng = 0
female_with_sheng = 0
female_without_sheng = 0
for name in names:
    if '胜' in name:
        if '男' in name:
            male_with_sheng += 1
        else:
            female_with_sheng += 1
    else:
        if '男' in name:
            male_without_sheng += 1
        else:
            female_without_sheng += 1
print('男性中带胜字的名字出现的频率为:{:.2%}'.format(male_with_sheng / (male_with_sheng + male_without_sheng)))
print('女性中带胜字的名字出现的频率为:{:.2%}'.format(female_with_sheng / (female_with_sheng + female_without_sheng)))

f = open('names.txt','r')
txt = f.read()
arr = txt.split()
sex = [0,0,0,0]
for i in range(len(arr)//2):
    sex[0 if arr[i * 2 + 1] == '男' else 1] += 1
    if arr[
手机没电要阵亡了

最好把你的代码贴一下
感觉是你没有读到女的数据
我写了一个给你参考下

male_count = 0
female_count = 0
male_sheng_count = 0
female_sheng_count = 0

with open('names.txt', 'r') as f:
    for line in f:
        name, gender = line.strip().split()
        if '胜' in name:
            if gender == '男':
                male_sheng_count += 1
            else:
                female_sheng_count += 1

        if gender == '男':
            male_count += 1
        else:
            female_count += 1

male_ratio = male_sheng_count / male_count if male_count > 0 else 0
female_ratio = female_sheng_count / female_count if female_count > 0 else 0

print('男性中包含“胜”字的人数:{}'.format(male_sheng_count))
print('女性中包含“胜”字的人数:{}'.format(female_sheng_count))
print('男性中包含“胜”字的比例:{}'.format(male_ratio))
print('女性中包含“胜”字的比例:{}'.format(female_ratio))

img