如何修复Python用户名生成器输出内容中间存在换行符的问题
问题根因
你遇到的输出换行问题确实是读取txt文件时每行末尾自带的换行符\n导致的:readlines()方法会默认保留每行末尾的换行符,因此你随机选中的形容词、名词末尾都会带一个看不见的\n,拼接后就会出现强制换行的效果。
之前用rstrip/strip/replace没生效,大概率是处理时机不对,比如只处理了其中一个变量,或者在拼接完成后才处理,最佳方案是在读取文件阶段就统一把所有条目的换行符清理掉,不需要手动修改原文件。
修复后的代码
只需要修改读取文件的两段逻辑即可:
from random import choice, randint username = "" # 读取时直接去除每行末尾的换行符 with open("./english-adjectives.txt", "r") as a: adjs = [line.rstrip('\n') for line in a] with open("./english-nouns.txt", "r") as b: nouns = [line.rstrip('\n') for line in b] caps = input("Enter yes if you want the 2 words to be capitalized and no if you don't: ").lower() under = input("Enter yes if you want an underscore between the 2 words: ").lower() nums = input("Enter yes if you want numbers at the end of the username: ").lower() if caps != "no": adj, noun = choice(adjs).capitalize(), choice(nouns).capitalize() else: adj, noun = choice(adjs), choice(nouns) username += adj username += f"_{noun}" if under == "yes" else noun if nums != "no": try: digits = int(input("Enter the number of digits that you want the number at the end of your username should be of: ")) # 额外优化:原randint(0,10)会生成10,导致出现两位数字,要单个0-9数字请改为randint(0,9) username += "".join(str(randint(0,9)) for _ in range(digits)) except ValueError: print("Please enter a valid value.") print(username)
补充说明
- 如果确认你的txt文件中每行单词前后没有多余空格,也可以将
rstrip('\n')替换为strip(),可以同时清理掉首尾所有空白字符 - 如果你坚持要在选中单词后再处理换行,也可以把取值逻辑改为
choice(adjs).rstrip('\n'),效果和提前处理一致,只是每次取值都要做一次处理,性能上略差一点,对于几千条的量级几乎无感知。
内容的提问来源于stack exchange,提问作者DhruvMitna19
相关产品推荐
相关产品推荐

