python - Python 3 函数多次打印同一个列表
问题描述
我需要这个函数来打印tastiera.txt
文件中的句子列表
def frasi_da_file():
arg1 = input ("percorso file: ")
arg2 = input("codifica: ")
if arg1 == "tastiera.txt" and arg2 == "latin1":
f = open("tastiera.txt")
raw = f.read()
for line in raw:
q = re.split("\s+", raw)
print (q)
现在它一遍又一遍地打印相同的列表......我认为问题出在“for”但我不知道如何解决它。
解决方案
以下是您的代码在“好 Python”中的样子:
with open("tastiera.txt") as f:
for line in f:
words = re.split("\s+", line) # words, not q!
print(words)
在这里使用正则表达式是可以的,尤其是在涉及非空白字符的情况下,但words = line.split()
更合适。
推荐阅读
- php - laravel - 正确使用 if 语句
- sequelize.js - Sequelize:同步后如何将数据插入新创建的表中
- javascript - 如何使用 Vuejs、vuex 将字符串转换为整数?
- facebook - Xamarin.Auth Facebook 登录完成事件未触发
- python - 检查请求中的身份验证信息是否正确
- javascript - 你如何“堆叠”单独列中的弹性元素?
- docker - Docker for Windows Kubernetes pod 在创建新部署后获取 ImagePullBackOff
- c# - 如何在局部空间中找到对象底部的位置?
- google-sheets - 将 Big Query 中的数据自动导入 Google 表格?
- python - 在 pymongo 中搜索时忽略一个特定或任何特殊字符