python - 正则表达式查找文本文件中字符串的所有出现位置。如何?

标签 python regex csv python-3.x io

第 1 步:生成 25 位十进制数字的 Pi 并将其保存到 output.txt 文件中。

from decimal import *

#Sets decimal to 25 digits of precision
getcontext().prec = 25

def factorial(n):
    if n<1:
        return 1
    else:
        return n * factorial(n-1)

def chudnovskyBig(): #http://en.wikipedia.org/wiki/Chudnovsky_algorithm
    n = 1
    pi = Decimal(0)
    k = 0
    while k < n:
        pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
        k += 1
    pi = pi * Decimal(10005).sqrt()/4270934400
    pi = pi**(-1)

    file = open('output.txt', 'w', newline = '')
    file.write(str(Decimal(pi)))
    file.close()
    print("Done.")

    #return pi

chudnovskyBig()

第 2 步:打开此文件并使用正则表达式查找特定字符串的所有匹配项。

import re

file = open('output.txt', 'r')

lines = file.read()

regex = input("Enter Combination: ")
match = re.findall(regex, lines)
print('Matches found: ' + str(len(match)))
file.close()
input("Press Enter to Exit.")

如何更改“查找所有匹配项”代码,以查看包含许多这些组合(每行一个)而不是一次仅一个的 csv 文件?

csv文件格式:

1\t2\t3\t4\t5\t6\r\n ..我认为?

1

最佳答案

以下是如何使用 re.findall 的示例

import re
pattern = '[A-Za-z0-9-]+' # pattern for matching all ASCII characters, digits, and repetitions of
                            # them (+)
lines = "property"           # adding input string, raw_input("Enter Combination: ")
ls = re.findall(pattern,lines)
print ls

关于python - 正则表达式查找文本文件中字符串的所有出现位置。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971487/

相关文章:

regex - 将文件分成多个文件

php - MySQL 替换为仅插入 .csv 中 54,000 条记录中的大约 14,000 条

python - RDD 只有第一列值 : Hbase, PySpark

python - 在 Python 中重新最大化 Tkinter 窗口

regex - 如何在vim中搜索所有大写单词?

javascript - 具有独特规则的 url 正则表达式

python - 如何替换Excel中的字符串并检查整个单元格字符串?

mysql - LOAD DATA LOCAL INFILE 给出错误 The used command is not allowed with this MySQL version

python - 如何编写一个累加器来围绕中点压缩数组?

python - 计算 ListView 中的帖子数量