我试图读取行来确定它的索引,以便在另一个程序中使用,但似乎总是传递一行特定的内容。为什么会这样
这是我的文本文件:
+-----------------------------------------------------------+
| Food Ordering System |
+-----------------------------------------------------------+
| No | Food | Price |
+-----------------------------------------------------------+
| 1. | Burger Set | RM11.00 |
+-----------------------------------------------------------+
| 2. | Pizza Set | RM11.00 |
+-----------------------------------------------------------+
| 3. | Spaghetti Bolognese Set | RM12.00 |
+-----------------------------------------------------------+
| 4. | Spaghetti Aglio Set | RM13.00 |
+-----------------------------------------------------------+
| No | Beverage | Price |
+-----------------------------------------------------------+
| 1. | Coca-Cola | |
+---------------------------------+ |
| 2. | Pepsi | Included in the set |
+---------------------------------+ |
| 3. | Fanta Strawberry | |
+---------------------------------+ |
| 4. | Fanta Orange | |
+-----------------------------------------------------------+
突出显示的是被忽略的图像
以下是我的代码和输出:
def Testing():
try:
data = []
with open("Menu.txt") as f:
for line in f:
if "-" not in line:
data.append(line.split("|")[1:-1])
print(data)
print((data[7][0]).strip())
print((data[7][1]).strip())
print((data[7][2]).strip())
except TypeError:
print("Invalid")
Testing()
输出:
[[' Food Ordering System '], [' No ', ' Food ', ' Price '], [' 1. ', ' Burger Set ', ' RM11.00 '], [' 2. ', ' Pizza Set ', ' RM11.00 '], [' 3. ', ' Spaghetti Bolognese Set ', ' RM12.00 '], [' 4. ', ' Spaghetti Aglio Set ', ' RM13.00 '], [' No ', ' Beverage ', ' Price '], [' 2. ', ' Pepsi ', ' Included in the set '], [' 3. ', ' Fanta Strawberry ', ' '], [' 4. ', ' Fanta Orange ', ' ']]
2.
Pepsi
Included in the set
如果您可以使用
pandas
库,这将是一个单行程序(包括拆分为单元格),请注意此正则表达式如何使用可选的周围空白指定管道“|”分隔符:现在“可口可乐”将被解析为一个字符串
(定义正则表达式比看起来要困难得多。我们必须同时匹配前导和尾随空格,并避开垂直条,以免被误解)
这一行:
由于
Coca-Cola
中的-
跳过该行看起来你想跳过这样的分界线
您需要使用不同的条件来跳过这些行,这样就不会跳过文本中包含
-
的行。例如:相关问题 更多 >
编程相关推荐