python - Python:如何删除列表中的数字
问题描述
Python学习者在这里。所以我有一个 wordlist.txt 文件,每行一个单词。我想过滤掉以特定字母开头和结尾的特定单词。但是在我的 wordlist.txt 中,单词是用它们的出现次数列出的。
例如:
food 312
freak 36
cucumber 1
这是我的代码
wordList = open("full.txt","r", encoding="utf-8")
word = wordList.read().splitlines()
for i in word:
if i.startswith("h") and i.endswith("e"):
print(i)
但是由于列表中的每个项目最后都有数字,我无法过滤正确的单词。我不知道如何省略这些数字。
解决方案
尝试使用空格作为分隔符来分割行,并使用第一个值[0]
,即你的情况下的单词
for i in word:
if i.split(" ")[0].startswith("h") and i.split(" ")[0].endswith("e"):
print(i.split(" ")[0])
或者你可以只执行一次拆分
for i in word:
w = i.split(" ")[0]
if w.startswith("h") and w.endswith("e"):
print(w)
编辑:根据下面的评论,如果碰巧有两个空格或一个制表符作为字段分隔符,您可能希望不使用参数或 None 进行拆分。
w = i.split()[0]
推荐阅读
- r - 错误:`data` 必须是一个数据框,或其他可被`fortify()` 强制的对象,而不是具有类 reactiveExpr/reactive 的 S3 对象
- lua - Lua 尝试调用索引全局 nil 值错误
- node.js - socket.io 无法连接 react-native 和 nodejs
- ocaml - 在 ocaml 中遇到矩阵问题
- typescript - 根据字段映射联合类型
- javascript - 如何从 rxjs observable 返回一个数组?
- python - 如何获取子目录列表?
- docker - 带有 asp.net 核心和 docker 的 ERR_EMPTY_RESPONSE
- java - 格式不正确的 Java 日期处理
- javascript - 在Angular 8中将两个基于不同键的对象数组合并为一个