python-3.x - 使用 Python3 在文件中查找表达式
问题描述
我正在用python3编写一个大学程序。该程序接受用户表达式和文件路径,然后在文件中找到包含该表达式的任何行。我现在的问题如下。
我有一个小的虚拟 txt 文件我用来测试它。该文件包含:
Hello, My name is Evan
This is a text file
I am using it to help me code my program
I am coding my program in Python3
我的主要Python文件如下:
# Necessary imports
import os
# Variables
userExpression = [] # Variable for user expression
userFile = [] # Variable for user file
fileLines = [] # Variable for lines of text in the users file
lineNum = 0 # Variable for keeping track of line numbers
userExpression = input("Please enter the expression you want to find: ") # Read in and store users expression
userFile = input("Enter the path of your file: ") # Read in and store file path of users file
myFile = open(userFile) # Opening user file
print(" ") # Used to make output easier to read
print("HOORAY!! File found!")
print("File lines that include your expressions are found below: ")
print(" ") # Used to make output easier to read
# Store each line of text into a list
for line in myFile:
lineNum += 1
if line.lower().find(userExpression) != -1:
fileLines.append("Line " + str(lineNum) + ": " + line.rstrip('\n'))
# Print out file text stored in list
for element in fileLines:
print(element)
myFile.close()
对于我的一项测试,我输入了“am”作为我想要查找的表达式。我得到了这个作为输出:
HOORAY!! File found!
File lines that include your expressions are found below:
Line 1: Hello, My name is Evan
Line 3: I am using it to help me code my program
Line 4: I am coding my program in Python3
问题是我的程序退出了第 1 行,因为 'name' 包含 'am'。有什么办法可以修复它,只输出第 3 行和第 4 行,因为它们特别包含“am”
解决方案
也许尝试检测“userExpression”(带空格),所以程序只能自己获取“userExpression”。
#like this
userExpression = " " + input("Please enter the expression you want to find: ") + " "
推荐阅读
- qt - 使用附加属性、信号的正确方法是什么?
- rust - 为什么在 rust 程序中运行 objcopy --strip-all 会使它们的大小减半?
- django - 在 Django 管理页面中创建用户时有条件地需要密码
- constraints - 改变滴蟑螂数据库约束
- sql - postgres 我们可以使用数组操作来执行 IN 或 ANY 运算符吗?
- cmake - Visual Studio 上的 CMake ExternalProject_Add 接收错误 MSB1009(但库构建)
- windows - LoadCursor 和混合 DPI 多显示器
- javascript - 本地图片的动态导入/加载
- python - 循环遍历动态 WTForm 中的字段
- javascript - 用javascript绘制像素化线?