python - 将 for 循环获取的三个值放入 DataFrame/Python 中

标签 python pandas dataframe

这个想法很简单,你打开一个文本文件,阅读它,发现字母重复了多少次,然后估计每个字母在文本中所占的百分比。

fileName = input("Enter file Name: ")
with open(fileName) as f:
    text = f.read()
print(text)

def count_char(text, char):
    count=0
    for c in text:
        if c == char:
            count+=1
    return count

for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "abcdefghijklmnopqrstuvwxyz":
    percentage = 100 * count_char(text, char) / len(text)
    print("\n letter: {0} is taking {1}% of the text and that is {2}".format(char, round(percentage,2), count_char(text, char)))

我确实设法做到了这一点,但我无法将这些值放入数据框中以看起来更加用户友好。

此外,如果用户输入的文件不存在(“错误 404 文件未找到!”)消息,我想制作一个 if-else 语句。

最佳答案

读入文件后,内容是名称为 text 的字符串。您可以将其传递给 pandas.value_counts 函数以获取每个字符的计数。为了仅过滤掉字母,我使用 filter 函数并传递 str.isalpha 作为谓词来确定每个字符的真实性。

pandas.value_counts

您的代码应如下所示:

import pandas as pd
import os

fileName = input("Enter file Name: ")
if os.path.exists(fileName):
    with open(fileName) as f:
        text = f.read()
else:
    print(("Error 404 File Not Found!")

counts = pd.value_counts([*filter(str.isalpha, text)]) / len(text)
print(counts)

a    0.064935
f    0.058442
q    0.051948
d    0.045455
r    0.045455
j    0.038961
e    0.032468
l    0.032468
k    0.032468
s    0.032468
t    0.032468
u    0.032468
i    0.032468
p    0.025974
w    0.025974
h    0.025974
g    0.019481
o    0.019481
y    0.012987
n    0.012987
T    0.006494
Q    0.006494
R    0.006494
dtype: float64
<小时/>

设置

text = """
a;sdlkfja;sldkfja
spogkia
;dlkfq
;welrfuq[3094t8urq34TRQaaj]
aksdfjpaoi43urpq9384t983456tuyweirghnwehrg
q34haed89fy9q9384uithnjlfasdf;q3p[er]q34t9rwiofdj"""

关于python - 将 for 循环获取的三个值放入 DataFrame/Python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867959/

相关文章:

python - 除了最后一列之外,我的数据框都有 NaN

pandas - 在随机森林中传递 Class_weight 参数时出现错误

python-3.x - 确定 Pandas 数组中的唯一用法

python - 在通配符/模式上解析 Python 中的文本文档行

python - 机器人框架+AutoIt : Dictionary does not contain key

Python Pandas : column with ordered file names based on given sequence

python - 连接两列

python - 在 python/pandas 中转置列

r - 数据集的 dplyr 字符串突变问题

Python 和 psycopg2 对大数据集的多处理性能